开发者

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 r开发者_如何学运维emoved.

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


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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜