我使用Backbone-Relational来创建复杂的模型层次结构,代码如下所示:
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
成功创建,initialize()
ModelA
也未被调用。检查类型证明集合中的对象不是ModelA
。我该如何解决这个问题?
答案 0 :(得分:0)
需要进行两项更改:将ModelA
设为RelationalModel
(而不仅仅是标准版),并告诉ModelB
ModelA
是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
}]
});
一样这样:
{{1}}