1

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

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

[{ 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 }]

如何在保留旧数据的同时使用新数据更新主干集合?ID 不是从服务器分配的(名称保证是唯一的)。

4

1 回答 1

0

I ended up going with this. This will update the properties for models that exist while also removing models that did not come in and adding new ones.

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);
};

Note the use of _prepareModel this is important so that the Models can be identified via whatever "id" property is used in the Backbone Model object.

于 2012-05-29T20:33:52.550 回答