2014-12-23 53 views
1

我用Backbone-Relational創建的模型層次複雜,代碼如下所示:如何處理嵌套在RelationalModel中的集合?

var ModelA = Backbone.Model.extend({ 
    initialize: function() { 
     console.log('model a initialized!') 
    } 
}); 

var CollectionA = Backbone.Collection.extend({ 
    model: ModelA 
}); 

var ModelB = Backbone.RelationalModel.extend({ 
    relations: [{ 
     type: Backbone.HasMany, 
     key: 'Collection', 
     collectionType: CollectionA 
    }] 
}); 

var data = new ModelB({ 
    name: 'ModelB', 
    Collection: [{ 
     name: 'ModelA-1' 
    }, { 
     name: 'ModelA-2' 
    }] 
}); 

console.log(data.get('Collection').at(0) instanceof ModelA); // false 
console.log(data.get('Collection').at(0) instanceof ModelB); // true 
console.log(JSON.stringify(data.toJSON())); 
// {"name":"ModelB","Collection":[{"name":"ModelA-1","Collection":[]},{"name":"ModelA-2","Collection":[]}]} 

正如你看到的,即使成功創建ModelBModelAinitialize()不叫。檢查類型證明集合中的對象不是ModelA。我怎樣才能解決這個問題?必要

回答

0

兩個變化:使ModelA一個RelationalModel(而不僅僅是一個標準),並告訴ModelBModelA是其relatedModel,像這樣:

var ModelA = Backbone.RelationalModel.extend({ 
    initialize: function() { 
     console.log('model a initialized!') 
    } 
}); 
... 

var ModelB = Backbone.RelationalModel.extend({ 
    relations: [{ 
     type: Backbone.HasMany, 
     relatedModel: 'ModelA', 
     key: 'Collection', 
     collectionType: CollectionA 
    }] 
}); 

Demo

+0

謝謝拉尼!你的回答解決了我的疑惑! – heyun