I'm trying to setup a little pair of models with Backbone Relational but I don't understand how the remove event is fired.
Here's my models code:
var Car = Backbone.RelationalModel.extend({
idAttribute: "id"
});
var Cars = Backbone.Collection.extend({
model: Car
});
var CarCollection = new Cars();
var User = Backbone.RelationalModel.extend({
idAttribute: 'id',
relations: [{
type: Backbone.HasMany,
key: 'model',
relatedModel: Car,
collectionType: Cars,
includeInJSON: 'model',
reverseRelation: {
key: 'ownedBy',
includeinJSON: 'name'
}
}]
});
var Users = Backbone.Collection.extend({
model: User
});
var UserCollection = new Users();
//Bootstrap data and put it in the collections
var carsData = [
{id:1, model:'500',ownedBy:1},
{id:2, model:'Corsa',ownedBy:2},
{id:3, model:'Civic',ownedBy:2}
];
var usersData = [
{id:1,name:'Dude'},
{id:2,name:'Mark'}
];
CarCollection.add(carsData);
UserCollection.add(usersData);
What I get, in JSON, is that:
UserCollection = {"id":1,"name":"Dude","model":["500"]}{"id":2,"name":"Mark","model":["Corsa","Civic"]}
CarCollection = {"id":1,"model":"500","ownedBy":"Dude"}{"id":2,"model":"Corsa","ownedBy":"Mark"}{"id":3,"model":"Civic","ownedBy":"Mark"}
Now if I add an element to CarCollection like this:
CarCollection.add({id:4,model:'Prius',ownedBy:1};);
The 'add' event is fired, but if I remove one element from the collection:
var el = CarCollection.get(1);
CarCollection.remove(el);
No event is fired.
I've resolved it with some workaround, like:
var el = CarCollection.get(1);
el.destroy();
or by unregister it directly in Backbone.store:
Backbone.Relational.store.unregister(el);
or just setting ownedBy to null:
var el = CarCollection.get(1);
el.set("ownedBy",null);
Is this the right behavior of the plugin? Or I've configured my models in the wrong way? Thanks for every answers.