我使用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。我怎样才能解决这个问题?

最佳答案

必须进行两项更改:将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
    }]
});


Demo

关于javascript - 如何处理嵌套在RelationalModel中的集合?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27627504/

10-09 20:26