Remove item from mast collection

I have the following code. Everything works fine, but I'm trying to figure out how to remove an item from the collection (note: I'm new to Backbone). I checked a few other posts, but I just can understand:

Todos = (function(){ ////////////////////////// // // MODEL // ////////////////////////// var TodoModel = Backbone.Model.extend({ defaults: { item: null } }); ////////////////////////// // // COLLECTION // ////////////////////////// var TodoCollection = Backbone.Collection.extend({ model: TodoModel }); ////////////////////////// // // VIEW // ////////////////////////// var TodoView = Backbone.View.extend({ el: $('#todos'), itemField: $('#new-item'), initialize: function(){ this.el = $(this.el); }, events: { 'submit form': 'addItem', 'click .remove-item': 'removeItem', // Debug 'click #print-collection': 'printCollection' }, template: $('#item-template').html(), render: function(i) { var templ = _.template(this.template); this.el.children('ul').append(templ({item: i})); }, addItem: function(e) { e.preventDefault(); item = this.itemField.val(); // Call render this.render(item); // Clear field this.itemField .val('') .focus(); // Add to collection var newItem = new TodoModel({ item: item }); this.collection.add(newItem); }, removeItem: function(e) { $(e.target).parent('li') .fadeOut(300,function() { $(this).remove(); }); // NEED TO REMOVE FROM COLLECTION... }, printCollection: function(){ this.collection.each(function(item) { console.log(item.get('item')); }); } }); ////////////////////////// // // SELF // ////////////////////////// self = {}; self.start = function(){ new TodoView({collection: new TodoCollection()}); }; return self; }); 
+6
source share
1 answer

You can use the base remove method to remove the model from the collection:

Remove the model (or array of models) from the collection. Triggers the delete event, which you can use to suppress silence. If you call back when listening to the delete event, the index at which the model is removed from the collection is available as options.index.

If you want to do this, you will need to have a way to capture the model that will be removed from the click event. There are two ways to do this:

  • Add the model identifier to the element that fires the event (say, like the data-id attribute), so the event handler can capture that identifier when it is called and use it to get the model (in which case, remove it from the collection).
  • Create a subview for each model that eliminates the need for an id attribute.

excellent post from Derick Bailey on the pros and cons of each approach, which I would recommend taking a look at (I 'basically rephrased it here).

Hope this helps.

+11
source

All Articles