0
我有一個Backbone.Model它看起來像:給予一個參考多個Backbone.Models
var 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
});
}
});
這個工程,是語義正確的,但感覺過度設計。額外的抽象層感覺沒有根據。
這是將屬性賦予模型的適當方法嗎?
當然,集合可以有一個屬性,但我覺得這是不好的做法,因爲Backbone沒有爲集合提供'默認值'。你認爲這是真的嗎? – 2014-10-20 16:22:52
爲什麼你需要'defaults'在你的情況下? 'platformInfo'屬性在從集合的構造函數調用的'initialize'方法中獲取默認值('null')。 – hindmost 2014-10-20 18:22:49