Cleanest way to destroy every Model in a Collection in Backbone

backbone.js

On the first attempt I wrote

this.collection.each(function(element){
    element.destroy();
});

This does not work, because it's similar to ConcurrentModificationException in Java where every other elements are removed.

I tried binding "remove" event at the model to destroy itself as suggested Destroying a Backbone Model in a Collection in one step?, but this will fire 2 delete requests if I call destroy on a model that belongs to a collection.

I looked at underscore doc and can't see a each() variant that loops backwards, which would solve the removing every element problem.

What would you suggest as the cleanest way to destroy a collection of models?

Thanks

Best Answer

You could also use a good, ol'-fashioned pop destroy-in-place:

var model;

while (model = this.collection.first()) {
  model.destroy();
}
Related Topic