2014-10-19 32 views
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 
     }); 
    } 
}); 

這個工程,是語義正確的,但感覺過度設計。額外的抽象層感覺沒有根據。

這是將屬性賦予模型的適當方法嗎?

回答

0

雖然骨幹類別可能不具有屬性,它們可以具有性質(以及任何對象),其可用於存儲共享數據。

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 : '' 
     }); 
    }}); 
}); 
+0

當然,集合可以有一個屬性,但我覺得這是不好的做法,因爲Backbone沒有爲集合提供'默認值'。你認爲這是真的嗎? – 2014-10-20 16:22:52

+0

爲什麼你需要'defaults'在你的情況下? 'platformInfo'屬性在從集合的構造函數調用的'initialize'方法中獲取默認值('null')。 – hindmost 2014-10-20 18:22:49