我有一个类似于:
的Backbone.Modelvar FooModel = Backbone.Model.extend({
defaults: {
details: '',
operatingSystem: ''
};
});
FooModel有很多实例存储在集合中:
var FooCollection = Backbone.Collection.extend({
model: FooModel
});
FooModel的OperatingSystem是一个只需要计算一次并异步派生的属性。例如:
chrome.runtime.getPlatformInfo(function(platformInfo){
console.log("Operating System: ", platformInfo.os);
});
如果我在FooModel级别执行此逻辑,那么每次实例化FooModel时都需要执行逻辑。所以,我认为这个操作应该在更高的层次上进行。但是,它是bad practice to give properties to a Backbone.Collection.
因此,这让我觉得我需要一个父模型:
var FooParentModel = Backbone.Model.extend({
defaults: {
platformInfo: '',
fooCollection: new FooCollection()
},
initialize: function() {
chrome.runtime.getPlatformInfo(function(platformInfo){
this.set('platformInfo', platformInfo);
}.bind(this));
},
// TODO: This will work incorrectly if ran before getPlatformInfo's callback
createFoo: function(){
this.get('fooCollection').create({
details: 'hello, world',
operatingSystem: this.get('platformDetails').os
});
}
});
这是有效的,并且在语义上是正确的,但感觉过度设计。额外的抽象层感觉没有根据。
这是将属性赋予模型的适当方法吗?
答案 0 :(得分:0)
虽然Backbone Collections可能没有属性,但它们可能具有属性(以及任何对象),您可以使用它来存储共享数据。
var FooCollection = Backbone.Collection.extend({
model: FooModel
initialize: function() {
this.platformInfo = null; // shared data
chrome.runtime.getPlatformInfo(function(platformInfo){
this.platformInfo = platformInfo;
}.bind(this));
},
// wrapper to create a new model within the collection
createFoo: function(details) {
this.create({
details: details,
operatingSystem: this.platformInfo? this.platformInfo.os : ''
});
}});
});