如何处理嵌套在关系模型中的集合



我使用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,也不会调用ModelA initialize()。检查类型证明集合中的对象未ModelA。我该如何解决这个问题?

需要

两个更改:使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
    }]
});

演示

相关内容

  • 没有找到相关文章

最新更新