从骨干集合筛选模型,然后为这些模型设置属性

Filtering models from a Backbone Collection and then setting attributes for those models

本文关键字:模型 属性 设置 然后 集合 筛选      更新时间:2023-09-26

this.model.collection.where({selected: true})返回模型数组

然后,我想将返回模型的selected属性设置为false。

我该怎么做?

@model.collection.where({selected: true})(咖啡脚本)

简单循环有什么问题?

m.set('selected', false) for m in @model.collection.where(selected: true)

甚至:

for m in @model.collection.where(selected: true)
    m.set('selected', false)

Undercore很好,但这并不意味着你必须在所有事情上都使用它。

您可以使用.each 执行此操作

_.each(this.model.collection.where({selected: true}), function(m){
    m.set('selected', false);
});

由于where返回一个匹配对象的数组,因此必须将该数组传递到下划线的each的第一个参数中。

您也可以使用map:进行此操作

this.model.collection.map(function(m){if(m.get('selected'){m.set('selected', false);}});

由于map获取集合(或数组)中的每个元素,并对它们应用一个方法。

this.model.collection.where({selected: true}).each(function(model){
    model.set({selected:false});
}