Search code examples
javascriptbackbone.js

avoid multiple remove events


I use backbone version 1.0.0 & underscore js. From my collection , i remove models that match some criteria.

myCollection.remove(myCollection.where({filterId: "1"}));

This will remove all the models inside my collection having filterId attribute == "1".

Now this is causing multiple change events for "remove" being fired when I have more than 1 model matching the criteria.

I want it to be fired only once when all matching models are removed. Please advice.


Solution

  • It is not possible to limit the remove event only once as Backbone triggers every time when a model is removed from a collection.

    Instead you can filter the collection and listen for reset event.

       var filtered = myCollection.filter(function(model) {
          return model.get("filterId") != 1;
        });
    
       myCollection.reset(filtered);