javascript - 在 Backbone 中批量更新手动模型集

标签 javascript backbone.js

我有一个包含以下模型的集合:

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 方法:

add collection.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/

相关文章:

javascript - 如何将 <div> 元素放在另一个元素之上

javascript - 为什么我无法访问 JSON 中的数据?

javascript - 检测 vimeo 视频何时暂停

javascript - 闭包编译器、​​主干和元编程

javascript - 你如何找到 Backbone 提取产生的错误

javascript - 球体的三个js buffergeometry

javascript - 将 HTTP POST 与 typeahead js 和 bloodhound js 一起使用

javascript - this.$el.html 与 this.$el.append

backbone.js - 在路由之间保留数据而不去服务器?

javascript - 在 backbone.js 中,如何使用新模型数据更新 View ,同时在没有完整渲染的情况下保持排序顺序