简体   繁体   English

骨干关系:未触发删除事件

[英]Backbone Relational: remove event not fired

I'm trying to setup a little pair of models with Backbone Relational but I don't understand how the remove event is fired. 我正在尝试使用Backbone Relational建立一些模型,但是我不了解如何触发remove事件。

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: 我在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"}

Now if I add an element to CarCollection like this: 现在,如果我像这样向CarCollection添加元素:

CarCollection.add({id:4,model:'Prius',ownedBy:1};);

The 'add' event is fired, but if I remove one element from the collection: “ add”事件被触发,但是如果我从集合中删除一个元素:

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.store中取消注册:

Backbone.Relational.store.unregister(el);

or just setting ownedBy to null: 或只是将ownedBy设置为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. 感谢您的每一个答案。

You have to pass a model to remove not the index 您必须通过模型才能remove索引

Collection.remove(model)

You can do the following: 您可以执行以下操作:

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

to remove the model with index 0 or ... 删除索引为0或...的模型

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

to remove the model with id 4 删除ID为4的模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM