Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 72 additions & 3 deletions published/understanding-backbone.md
Original file line number Diff line number Diff line change
Expand Up @@ -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('<li>' + status.escape('text') + '</li>');
- }
+ },
+
+ $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!
---------------

Expand All @@ -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');
}
});

Expand All @@ -1490,7 +1555,11 @@ var StatusesView = Backbone.View.extend({
},

appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape('text') + '</li>');
this.$ul().append('<li>' + status.escape('text') + '</li>');
},

$ul: function() {
return this.$('ul');
}
});

Expand Down