this.each不是通过遍历集合正确 [英] this.each not iterating through collection correctly

查看:108
本文介绍了this.each不是通过遍历集合正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Backbone.js的,我加入了一些基本的方法来扩展集让我迭代通过集合并保存所有车型,并迭代通过集合销毁所有车型。我认识到,批量更新不是RESTful的,但我只更新到本地存储所以没想到会做多次更新的问题。

I've just started using backbone.js and I'm adding some basic methods to extend a collection allowing me to iterate through a collection and save all models, and iterate through a collection to destroy all models. I realise that bulk updates aren't RESTful, but I'm only updating to local storage so didn't think it would be an issue to do multiple updates.

在我的基本应用程序,收集有9款车型。
当我打电话collection.saveModels()它正确记录集的长度,和正确保存所有的模型。

In my base application, the collection has 9 models. When I call collection.saveModels() it correctly logs the length of the collection, and correctly saves all the models.

当我打电话collection.deleteModels()它正确记录集的长度,但每跳过第二个模型(即第2,第4,第6,第8)。每次删除为pressed它仍然只删除索引奇元素,最后一个项目是第8原始项目被删除。

When I call collection.deleteModels() it correctly logs the length of the collection, but skips every second model (i.e. the 2nd, 4th, 6th, 8th). Each time delete is pressed it continues to only delete the odd indexed element, with the last item to be deleted being the 8th original item.

是否有可能我使用的每一个功能不正确,尽管它完美地工作时我救?

Is it possible I'm using the each function incorrectly, despite it working perfectly when I save?

_.extend(Backbone.Collection.prototype, Backbone.Events, {
saveModels  :   function() {
    console.log(this.length);
    this.each(function(model){
        console.log('saving model ' + model.get('name'));
        model.save();
    });
},
deleteModels    :   function() {
    console.log(this.length);
    this.each(function(model){
        console.log('deleting model ' + model.get('name'));
        model.destroy();
    });
}
});

和他们被称为像这样: mycollection.saveModels(); mycollection.deleteModels();

and they are called like so: mycollection.saveModels(); and mycollection.deleteModels();

我知道我可以通过基于长度集合迭代,但我宁愿使用内置的方法,其中可能的。

I realise I can iterate through the collection based on length, but I'd rather use the built in method where possible.

推荐答案

在code bradgonesurfing贴不实际工作作为克隆方法不返回下划线的对象。正确的方法是使用 _.chain 的方法,使每个方法可链接。

The code bradgonesurfing posted doesn't actually work as the clone method doesn't return an underscore object. The correct way is to use the _.chain method with makes each method chainable.

_.chain(App.articles.models).clone().each(function(model){
  console.log('deleting model ' + model.get('name'));
  model.destroy();
});

这篇关于this.each不是通过遍历集合正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆