我正在尝试使用Backbone Relational设置一对模型,但我不明白如何触发remove事件。
这是我的模型代码:
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);
我在JSON中得到的是:
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"}
现在,如果我像这样向CarCollection添加一个元素:
CarCollection.add({id:4,model:'Prius',ownedBy:1};);
触发'add'事件,但是如果我从集合中删除一个元素:
var el = CarCollection.get(1);
CarCollection.remove(el);
没有发生任何事件。
我已经通过一些解决方法解决了这个问题,例如:
var el = CarCollection.get(1);
el.destroy();
或直接在Backbone.store中取消注册:
Backbone.Relational.store.unregister(el);
或只是将ownedBy设置为null:
var el = CarCollection.get(1);
el.set("ownedBy",null);
这是插件的正确行为吗?或者我以错误的方式配置了我的模型?谢谢你的每一个答案。
答案 0 :(得分:0)
您必须将模型传递给remove
而不是索引
Collection.remove(model)
您可以执行以下操作:
CarCollection.remove(CarCollection.at(0));
删除索引为0或...的模型
CarCollection.remove(CarCollection.get(4));
删除id为4的模型