【问题标题】:Update model within collection where model attribute is x更新模型属性为 x 的集合中的模型
【发布时间】:2015-08-26 18:57:06
【问题描述】:

在主干中,我有一个集合。如果模型具有特定的属性值,我想在其中更新一个或多个模型。

我知道我可以做到的程度

var model = myCollection.where({some_attr:'something'});

model 成为集合中的子对象。但除此之外,我似乎迷路了。因为似乎没有一个主干功能可以处理它。例如,我不能:

model.set({other_attr: 'changed value'});
model.save();

我刚刚得到一个未捕获的类型错误。 model.set is not a function

再次..示例清酒。

所以总的来说我想找到模型,更新它,然后将它和它的更改保存到服务器?想法?假设我没有可用的 ID 来让获取和设置变得更容易,因此我需要做一个 where 并像这样更新。

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    我建议使用where 并始终使用它传递的模型数组。完成模型更新后,您可以对集合进行 sync 调用,以将这些更改批量更新回服务器。

    myCollection.
      where({some_attr:'something'}).
      map(function(model) {
        model.set({other_attr: 'changed value'});
      });
    myCollection.sync('update');
    

    【讨论】:

      【解决方案2】:

      声明

      var model = myCollection.where({some_attr:'something'});
      

      返回一个模型数组,而不是单个模型。假设只有一个模型符合您的条件,您可以使用

      var model = myCollection.findWhere({some_attr:'something'});
      

      如果您的集合可能有多个匹配模型,那么您将希望坚持使用.where,但要遍历数组。

      【讨论】:

        猜你喜欢
        • 2015-08-04
        • 2012-01-21
        • 2013-11-19
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多