如何处理嵌套在RelationalModel中的集合?

时间:2014-12-23 20:24:05

标签: javascript backbone.js backbone-relational

我使用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。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

需要进行两项更改:将ModelA设为RelationalModel(而不仅仅是标准版),并告诉ModelB ModelArelatedModel,就像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}}

Demo