简体   繁体   English

从 backbone.js 集合中删除每个 model

[英]Removing each model from a backbone.js collection

I'm trying to iterate through a backbone collection and move each item to another collection.我正在尝试遍历主干集合并将每个项目移动到另一个集合。 While iterating through and removing items only half the items are removed.在迭代和删除项目时,只有一半的项目被删除。

app.cloud.each(function(model){
    app.cloud.remove(model);
    app.tail.add(model);
})

Can anyone suggest a nice way of addressing this issue?任何人都可以提出一个解决这个问题的好方法吗? Ideally I wan't to keep the code as readable as possible.理想情况下,我不想让代码尽可能地可读。

You're modifying the collection as you're iterating over it.您在迭代集合时正在修改集合。 I don't know backbone very well, but I venture to say that this will produce weird results.我不太了解骨干,但我敢说这会产生奇怪的结果。

A possible fix is to change your approach so that first you add everything to app.tail by iterating over app.cloud and then clear app.cloud一个可能的解决方法是更改您的方法,以便首先通过迭代app.cloud将所有内容添加到app.tail ,然后清除app.cloud

I'm not sure of the reason for wanting to move all models to a new collection but... I'd suggest not iterating over it yourself - let Backbone take care of it.我不确定要将所有模型移动到新系列的原因,但是......我建议不要自己迭代它 - 让 Backbone 来处理它。 I haven't tried the following but should work.我没有尝试以下但应该工作。

app.tail.add(app.cloud.toJSON());
app.cloud.reset();

To be safer you'd want to reset app.cloud when the add event fires in app.tail.为了更安全,您希望在 app.tail 中触发add事件时重置app.cloud。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM