Created
February 8, 2012 14:16
-
-
Save ericallam/1769878 to your computer and use it in GitHub Desktop.
How do you handle a collection's remove event in a collection view?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var TodoItem = Backbone.Model.extend({}); | |
var TodoView = Backbone.View.extend({ | |
template: _.template('<h3><%= description %></h3>'), | |
initialize: function(){ | |
this.model.bind('change', this.render, this); | |
this.model.on('destroy', this.remove, this); | |
}, | |
render: function(){ | |
this.$el.html(this.template(this.model.toJSON())); | |
return this; | |
}, | |
remove: function(){ | |
this.$el.remove(); | |
} | |
}); | |
var TodoItems = Backbone.Collection.extend({ | |
model: TodoItem | |
}); | |
var TodosView = Backbone.View.extend({ | |
initialize: function(){ | |
this.collection.on('add', this.addOne, this); | |
this.collection.on('reset', this.addAll, this); | |
}, | |
render: function(){ | |
this.addAll() | |
return this; | |
}, | |
addAll: function(){ | |
this.collection.forEach(this.addOne); | |
}, | |
addOne: function(todoItem){ | |
var todoView = new TodoView({model: todoItem}); | |
this.$el.append(todoView.render().el); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment