我有一个“ Assets ”主干模型,它有一个名为“selected”的自定义属性。从某种意义上说,它不是服务器端对象的一部分。我用来表示用户当前选择了哪些 Assets 列表。
var Asset = Backbone.Model.extend({
defaults: {
selected: false
},
idAttribute: "AssetId"
});
这个模型是我定期获取的主干集合的一部分,以从服务器获取任何更改。
我遇到的问题是,每次我获取集合时,集合都会进行重置(我可以通过监听重置事件来判断),因此所选属性的值会被来自 ajax 的数据清除要求。
Backbone.js 文档似乎暗示有一个智能合并可以解决这个问题。我相信我在我的 fetch 方法中这样做
allAssets.fetch({ update: true ,cache: false});
而且我还在模型中设置了“idAttribute”字段,以便可以将传入的对象的 id 与集合中的对象进行比较。
我解决这个问题的方法是在我的集合对象中编写我自己的 Parse 方法
parse: function (response) {
// ensure that the value of the "selected" for any of the models
// is persisted into the model in the new collection
this.each(function(ass) {
if (ass.get("selected")) {
var newSelectedAsset = _.find(response, function(num) { return num.AssetId == ass.get("AssetId"); });
newSelectedAsset.selected = true;
}
});
return response;
}
有一个更好的方法吗?
最佳答案
Collection.update (在 Backbone 0.9.9 中引入)确实尝试合并现有模型,但通过将新模型中的所有设置属性合并到旧模型来实现。如果您检查 Backbone source code , 你会看到的
if (existing || this._byCid[model.cid]) {
if (options && options.merge && existing) {
existing.set(model.attributes, options);
needsSort = sort;
}
models.splice(i, 1);
continue;
}
所有属性(包括默认值)都已设置,这就是您选择的属性重置为 false 的原因。删除 selected 的默认值将按预期工作:比较 http://jsfiddle.net/nikoshr/s5ZXN/至 http://jsfiddle.net/nikoshr/s5ZXN/3/
也就是说,我不会依赖模型属性来存储我的应用程序状态,我宁愿将它移动到其他地方的 Controller 。
关于backbone.js - 如何通过集合获取保留自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983470/