Backbone.js如何清空一个集合?

5
我需要清空一个集合,按顺序删除每个项目。
this.nodes.each(function(node){
  this.nodes.remove(node);
}, this);

由于每个节点的移除都会改变集合的长度,因此不起作用。制作一个临时数组,然后对其进行迭代即可解决问题。是否有更好的方法?
4个回答

4
尝试使用this.nodes.reset(),除非您需要remove事件。
否则:
var nodes = this.nodes;
while (nodes.length > 0)
    nodes.remove(nodes.at(0));

是的,我需要在每个节点上移除事件,因为它会清除其他东西。 - forresto

2

清空backbone集合的另一种方法:

while ( this.catz.length > 0) this.catz.pop();

1
如果您需要在迭代时修改集合,请使用简单的反向 for 进行操作,如下所示:
var count = collection.size();
for (var i = count-1; i > -1; i--) {
    collection.remove(collection.at(i));
}

http://jsfiddle.net/xt635/上试验


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接