diff --git a/published/understanding-backbone.md b/published/understanding-backbone.md index 8efb74c..f6c507b 100644 --- a/published/understanding-backbone.md +++ b/published/understanding-backbone.md @@ -1450,6 +1450,67 @@ engines, you might get this functionality out of the box. }); ``` +Split jQuery selectors into functions +--------------- + +``` diff +var Status = Backbone.Model.extend({ + url: '/status' +}); + +var Statuses = Backbone.Collection.extend({ + model: Status +}); + +var NewStatusView = Backbone.View.extend({ + events: { + 'submit form': 'addStatus' + }, + + initialize: function() { + this.collection.on('add', this.clearInput, this); + }, + + addStatus: function(e) { + e.preventDefault(); + +- this.collection.create({ text: this.$('textarea').val() }); ++ this.collection.create({ text: this.$textarea().val() }); + }, + + clearInput: function() { +- this.$('textarea').val(''); ++ this.$textarea().val(''); +- } ++ }, ++ ++ $textarea: function() { ++ return this.$('textarea'); ++ } +}); + +var StatusesView = Backbone.View.extend({ + initialize: function() { + this.collection.on('add', this.appendStatus, this); + }, + + appendStatus: function(status) { + this.$ul().append('
  • ' + status.escape('text') + '
  • '); +- } ++ }, ++ ++ $ul: function() { ++ return this.$('ul'); ++ } +}); + +$(document).ready(function() { + var statuses = new Statuses(); + new NewStatusView({ el: $('#new-status'), collection: statuses }); + new StatusesView({ el: $('#statuses'), collection: statuses }); +}); +``` + And we're done! --------------- @@ -1476,11 +1537,15 @@ var NewStatusView = Backbone.View.extend({ addStatus: function(e) { e.preventDefault(); - this.collection.create({ text: this.$('textarea').val() }); + this.collection.create({ text: this.$textarea().val() }); }, clearInput: function() { - this.$('textarea').val(''); + this.$textarea().val(''); + }, + + $textarea: function() { + return this.$('textarea'); } }); @@ -1490,7 +1555,11 @@ var StatusesView = Backbone.View.extend({ }, appendStatus: function(status) { - this.$('ul').append('
  • ' + status.escape('text') + '
  • '); + this.$ul().append('
  • ' + status.escape('text') + '
  • '); + }, + + $ul: function() { + return this.$('ul'); } });