0

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

这是我的模型代码:

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

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

4

1 回答 1

0

您必须将模型传递给remove索引

Collection.remove(model)

您可以执行以下操作:

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

删除索引为 0 的模型或...

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

删除 id 为 4 的模型

于 2012-12-18T14:07:59.340 回答