2012-10-17 88 views
5

我需要清空集合,按順序刪除每個項目。backbone.js清空集合

this.nodes.each(function(node){ 
    this.nodes.remove(node); 
}, this); 

不起作用,因爲每個節點都被移除,它會改變集合的長度。製作一個臨時數組,然後遍歷該作品。有沒有更好的辦法?

回答

4

嘗試this.nodes.reset()除非您需要remove事件。

否則:

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

是的,我需要每個節點上的remove事件,因爲它正在清除其他的東西。 – forresto

+1

@forresto,已更新 –

1

如果您需要在迭代修改集合,那麼就使用簡單的落後for喜歡它:

var count = collection.size(); 
for (var i = count-1; i > -1; i--) { 
    collection.remove(collection.at(i)); 
} 

小提琴在http://jsfiddle.net/xt635/

+0

按照相反的順序移除即可。 – forresto

2

另一種方式空骨幹收藏:

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