I use Backbone-Relational to create a complex hierarchy of models, the code looks like this:
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":[]}]}
As you see, even though ModelB
is successfully created, initialize()
of ModelA
isn't called. Checking the types proves that the objects inside the collection are not ModelA
. How can I fix this?
Two changes necessary: make ModelA
a RelationalModel
(and not just a standard one), and tell ModelB
that ModelA
is its relatedModel
, like this:
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.