Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
forresto Avatar asked Oct 17 '12 14:10

forresto


2 Answers

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

Otherwise:

var nodes = this.nodes;
while (nodes.length > 0)
    nodes.remove(nodes.at(0));
like image 192
rinat.io Avatar answered Sep 16 '22 13:09

rinat.io


Another way to empty of backbone collection:

while ( this.catz.length > 0) this.catz.pop();
like image 29
PRASS Avatar answered Sep 17 '22 13:09

PRASS