我有一个模型主干集合,这些页面加载的数据与获取时的数据不同。

例如,页面加载中出现的属性是:

[{ name: 'cat', color: 'yellow' },
 { name: 'dog', color: 'brown' },
 { name: 'fish', color: 'orange' }]


然后,在fetch()上(或在页面存在时从服务器更新),数据如下所示:

[{ name: 'cat', current: 5, total: 100 },
 { name: 'dog', current: 6, total: 50 },
 { name: 'fish', current:7, total: 25 }]


如何在保留旧数据的同时用新数据更新Backbone Collection?未从服务器分配ID(保证名称唯一)。

最佳答案

我结束了这个。这将更新现有模型的属性,同时删除不存在的模型并添加新模型。

Backbone.Collection.prototype.update = function(col_in){
  var self = this,
      new_models = [];

  _(col_in).each(function(mod_in) {
    var new_model = self._prepareModel(mod_in),
        mod = self.get(new_model.id);
    if (mod) {
      new_models.push(mod.set(mod_in, {silent:true}));
    } else {
      new_models.push(mod_in);
    }
  });

  this.reset(new_models);
};


请注意,使用_prepareModel这很重要,因此可以通过在主干模型对象中使用的任何“ id”属性来标识模型。

10-04 14:59
查看更多