17

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

7 Answers 7

34

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

var model;

while (model = this.collection.first()) {
  model.destroy();
}
3
  • I tried this but it gave me A "url" property or function must be specified error. Changing pop() to first() or last() fixed it. Commented Mar 24, 2013 at 14:35
  • Thanks, @david--that's a really good point! If the model URL is being inferred from the collection, removing the model will trigger this error. I'll fix the answer.
    – rjz
    Commented Mar 24, 2013 at 15:04
  • 4
    Destroying a backbone model will trigger a DELETE api call - which throws the A "url" property or function must be specified error. You need to first model.id = null then you can `model.destroy()'
    – yellowaj
    Commented Jul 19, 2013 at 16:00
25

I recently ran into this problem as well. It looks like you resolved it, but I think a more detailed explanation might also be useful for others that are wondering exactly why this is occurring.

So what's really happening?

Suppose we have a collection (library) of models (books).

For example:

console.log(library.models); // [object, object, object, object]

Now, lets go through and delete all the books using your initial approach:

library.each(function(model) {
  model.destroy();
});

each is an underscore method that's mixed into the Backbone collection. It uses the collections reference to its models (library.models) as a default argument for these various underscore collection methods. Okay, sure. That sounds reasonable.

Now, when model calls destroy, it triggers a "destroy" event on the collection as well, which will then remove its reference to the model. Inside remove, you'll notice this:

this.models.splice(index, 1);

If you're not familiar with splice, see the doc. If you are, you can might see why this is problematic.

Just to demonstrate:

var list = [1,2];
list.splice(0,1); // list is now [2]

This will then cause the each loop to skip elements because the its reference to the model objects via models is being modified dynamically!

Now, if you're using JavaScript < 1.6 then you may run into this error:

Uncaught TypeError: Cannot call method 'destroy' of undefined

This is because in the underscore implementation of each, it falls back on its own implementation if the native forEach is missing. It complains if you delete an element mid-iteration because it still tries to access non-existent elements.

If the native forEach did exist, then it would be used instead and you would not get an error at all!

Why? According to the doc:

If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time forEach visits them; elements that are deleted are not visited.

So what's the solution?

Don't use collection.each if you're deleting models from the collection. Use a method that will allow you to work on a new array containing the references to the models. One way is to use the underscore clone method.

_.each(_.clone(collection.models), function(model) {
  model.destroy();
});
2
  • This should be the correct answer, thnx for the info Commented Aug 4, 2014 at 18:48
  • Thanks so much. This was my first foray at messing with bbjs, and I decided to try to delete an entire collection piece-by-piece. I was shocked to see a smattering of items removed each pass! This explains what was happening superbly and removes some of the black magic from bbjs. Commented Dec 26, 2014 at 22:20
13

I'm a bit late here, but I think this is a pretty succinct solution, too:

_.invoke(this.collection.toArray(), 'destroy');
4
  • 1
    Nice! We could even apply it to the collection directly: this.collection.invoke('destroy');
    – rjz
    Commented Jun 18, 2014 at 4:44
  • 1
    There was something about calling toArray that was important... but I don't remember a year later. :( Commented Jun 18, 2014 at 6:16
  • 2
    Quite possibly that collection iteration doesn't work gracefully if we're destroy elements as we go? Either way-- toArray is still a nice, tidy answer. If it works, let's go with that! :^)
    – rjz
    Commented Jun 18, 2014 at 12:36
  • 1
    I suspect you're correct. Invoke probably iterates over the elements and if you destroy it without creating a copy beforehand then the iteration will break, but not 100%. Commented Jun 18, 2014 at 18:14
1

Piggybacking on Sean Anderson answer. There is a direct access to backbone collection array, so you could do it like this.

_.invoke(this.collection.models, 'destroy');

Or just call reset() on the collection with no parameters, destroy metod on the models in that collection will bi triggered.

this.collection.reset(); 

http://backbonejs.org/#Collection-models

0

This works, kind of surprised that I can't use underscore for this.

for (var i = this.collection.length - 1; i >= 0; i--)
    this.collection.at(i).destroy();
0

I prefer this method, especially if you need to call destroy on each model, clear the collection, and not call the DELETE to the server. Removing the id or whatever idAttribute is set to is what allows that.

var myCollection = new Backbone.Collection();
var models = myCollection.remove(myCollection.models);
_.each(models, function(model) {
  model.set('id', null); // hack to ensure no DELETE is sent to server
  model.destroy();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>

0

You don't need underscore and for loop for this.

this.collection.slice().forEach(element => element.destroy());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.