Search code examples
javascriptcollectionsbackbone.js

backbone.js empty a collection


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?


Solution

  • Try this.nodes.reset() unless you need remove event.

    Otherwise:

    var nodes = this.nodes;
    while (nodes.length > 0)
        nodes.remove(nodes.at(0));