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":[]}]}
正如你看到的,即使成功創建ModelB
的ModelA
initialize()
不叫。檢查類型證明集合中的對象不是ModelA
。我怎樣才能解決這個問題?必要
謝謝拉尼!你的回答解決了我的疑惑! – heyun