Skip to content

Instantly share code, notes, and snippets.

@ericallam
Created February 8, 2012 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericallam/1769878 to your computer and use it in GitHub Desktop.
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?
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