主干关系:删除未触发的事件



我正在尝试使用骨干关系设置一对模型,但我不明白删除事件是如何触发的。

这是我的模型代码:

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);

这是插件的正确行为吗?或者我以错误的方式配置了我的模型?感谢您的每一个答案。

你必须传递一个模型来remove而不是索引

Collection.remove(model)

您可以执行以下操作:

CarCollection.remove(CarCollection.at(0));

删除索引为 0 或 ...

CarCollection.remove(CarCollection.get(4));

删除 ID 为 4 的模型

相关内容

  • 没有找到相关文章

最新更新