我有一个包含以下模型的集合:
rows: [
id: 1
category: 'Meetings & Banquets'
progress: 0.8
,
id: 2
category: 'Guest Services'
progress: '50%'
,
id: 3
category: 'Concessionaires'
progress: '20%'
,
id: 4
category: 'Telecommunications'
progress: 100
,
id: 5
category: 'Restaurant'
progress: '70%'
]
我想像这样批量更新其中两个,并让绑定(bind)到 View 的模型自行更新:
rows: [
id: 1
category: 'Meetings & Banquets'
progress: 0.9
,
id: 2
category: 'Guest Services'
progress: '10%'
,
]
当我对集合执行 .add 或 .reset 时,它会阻止我添加/更新具有相同 ID 的模型。我有哪些选项可以批量更新这些模型?
最佳答案
编辑:在主干网 0.9.9 中,您现在可以使用带有选项 {merge: true}
的 add
方法:
addcollection.add(models, [options])
If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true}, in which case their attributes will be merged into the corresponding models, firing any appropriate "change" events.
我不相信现在在主干集合中有一个函数可以为你做这件事。也许您可以创建自己的?
MyCollection = Backbone.Collection.extend({
model: MyItem,
update: function(updatedArray) {
var that = this;
_.each(updateArray, function(element) {
if(that.get(element.id)) {
that.get(element.id).set(element);
}
});
}
});
然后:
var collection = new MyCollection(rows); //creates your collection
collection.update(rows2); //updates specific models.
关于javascript - 在 Backbone 中批量更新手动模型集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13771957/