Remove Item From Backbone Collection

22,749

You can use backbone's remove method to remove a model from a collection:

Remove a model (or an array of models) from the collection. Fires a "remove" event, which you can use silent to suppress. If you're a callback listening to the "remove" event, the index at which the model is being removed from the collection is available as options.index.

If you want to do this though, you'll have to have a way to grab the model to be removed from the click event. There are basically two ways to do this:

  1. Add the model's id to the element that triggers the event (say as a data-id attribute), so that the event handler can grab that id when it is called and use it to get the model (and in this case remove it from the collection).
  2. Create a sub-view for each model rendered, which obviates the need for an id attribute.

There is a great post by Derick Bailey on the pros and cons of each approach that I'd recommend having a look at (I've basically paraphrased him here).

Hope that helps.

Share:
22,749
Fluidbyte
Author by

Fluidbyte

I am an architect/engineer from Wisconsin working primarily in the JavaScript/NodeJS ecosystem with a passion for process/task automation, CI, and Docker.

Updated on July 09, 2022

Comments

  • Fluidbyte
    Fluidbyte almost 2 years

    I have the following code. Everything works perfectly, but I'm trying to figure out how to remove an item from the collection (note: I'm new to Backbone). I've checked out several other posts but I just can seem to figure it out:

    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;
    
    });