Search code examples
javascriptbackbone.jsbackbone.js-collections

Backbone.js remove model from collection


I'm learning Backbone and for the life of me I can't remove a model from a collection. The collection 'remove' event fires, but the collection appears to remain the same. Here's what I have so far: http://jsbin.com/becamo/edit?js,output

I remove the model from the collection upon click.

Then, the list view is listening for the collection remove event and calls render() again.

I can see from a console.log() that the remove event fires, but nothing changes. And when I inspect the collection variable it's unchanged. I've tried probably 50 variations now whilst searching the internet for clues and nothing seems to work.


Solution

  • You do not need to implement remove on the collection -- simply removing your attempt to override the default fixes the issue. So the collection implementation becomes:

    var UserCollection = Backbone.Collection.extend({
      model: User
    });
    

    Instead of:

    var UserCollection = Backbone.Collection.extend({
      model: User,
      initialize: function() {
        this.on('remove', this.remove);
      },
      remove: function() {
        console.log('Collection Event: REMOVE');
      }
    });
    

    http://jsbin.com/jefudiyido/1/edit?js,output