Reputation: 12388
I need to empty a collection, removing each item in order.
this.nodes.each(function(node){
this.nodes.remove(node);
}, this);
Doesn't work, because as each node is removed it changes the length of the collection. Making a temporary array and then iterating over that works. Is there a better way?
Upvotes: 5
Views: 3953
Reputation: 29
http://backbonejs.org/#Collection-reset
You can call collection.reset();
and it'll empty the entire collection. I used it today!
Upvotes: 1
Reputation: 315
Another way to empty of backbone collection:
while ( this.catz.length > 0) this.catz.pop();
Upvotes: 2
Reputation: 671
If you need to modify collection while iterating, then do it using a simple backward for
like that:
var count = collection.size();
for (var i = count-1; i > -1; i--) {
collection.remove(collection.at(i));
}
Fiddle at http://jsfiddle.net/xt635/
Upvotes: 1
Reputation: 3188
Try this.nodes.reset()
unless you need remove
event.
Otherwise:
var nodes = this.nodes;
while (nodes.length > 0)
nodes.remove(nodes.at(0));
Upvotes: 4