2013-08-06 181 views
0

我在我的腦海裏有這樣的模型結構內部的集合:綁定嵌套模型

var app = app || {}; 

// Caratteristica 
app.Attribute = Backbone.Model.extend({ 
    defaults: {  
     name: '', 
     selected: false 
    } 
}); 

app.Attributes = Backbone.Collection.extend({ 
    model: app.Attribute 
}); 

// Tipo Caratteristica 
app.AttributeCategory = Backbone.Model.extend({ 
    defaults: {  
     name: '', 
     attributes: new app.Attributes() 
    } 
}); 

app.AttributeCategories = Backbone.Collection.extend({ 
    model: app.AttributeCategory, 
    url: '/ajax/attributes.cfm' 
}); 

我在「/ajax/attributes.cfm」 API會給我這樣的迴應:

[ 
    { 
     "id": "1", 
     "name": "Type1", 
     "attributes": [ 
      { 
       "id": "1", 
       "name": "Attribute1" 
      }, 
      { 
       "id": "2", 
       "name": "Attribute2" 
      }, 
      { 
       "id": "3", 
       "name": "Attribute3" 
      } 
     ] 
    }, 
    { 
     "id": "2", 
     "name": "Type2", 
     "attributes": [ 
      { 
       "id": "1234", 
       "name": "Attribute1234" 
      }, 
      { 
       "id": "2567", 
       "name": "Attribute2567" 
      } 
     ] 
    } 
] 

我的問題是:將這個json數據正確解析成我的嵌套數據結構? 我的意思是我想最終有兩個app.AttributeCategory項目在我的app.AttributeCategories集合。這兩個項目中的每一個必須具有其屬性屬性填充相應的應用程序。屬性集合。

如果答案是否定的,我將如何覆蓋解析()函數來實現該結果?

回答

0

您可以創建集合的初始化方法裏面你AttributeCategory模型中,像這樣:

app.AttributeCategory = Backbone.Model.extend({ 

    ... 

    initialize: function() { 
     this.set('attributes', new app.Attributes(this.get('attributes'))); 
    } 
}); 
1

我做了這樣的:

// Tipo Caratteristica 
app.AttributeCategory = Backbone.Model.extend({ 
    defaults: {  
     name: '' 
    }, 
    initialize: function(options) { 
     this.set('attributes', new app.Attributes(options.attributes)); 
     Backbone.Model.prototype.apply(this, arguments); 
    } 
}); 

但更好地利用RationalModel爲建立關係的中間人模型