删除集合中的模型并触发删除事件 - backbone.js

时间:2013-02-25 13:24:49

标签: javascript backbone.js

如何删除集合中的模型并使remove事件触发。我试过people.remove([{ name: "joe3" }]);,但它无法正常工作。

var Person = Backbone.Model.extend({

    initialize: function () {
        console.log(" person is initialized");
    },
    defaults: {
        name: "underfined",
        age:"underfined"
    }
});

var People = Backbone.Collection.extend({
    initialize: function () {
        console.log("people collection is initialized");
        this.bind('add', this.onModelAdded, this);
        this.bind('remove', this.onModelRemoved, this);
    },
    model: Person,
    onModelAdded: function(model, collection, options) {
        console.log("options = ", options);
        alert("added");
    },
    onModelRemoved: function (model, collection, options) {
        console.log("options = ", options);
        alert("removed");
    },
});

//var person = new Person({ name: "joe1" });
var people = new People();



//people.add([{ name: "joe2" }]);
people.add([{ name: "joe1" }]);
people.add([{ name: "joe2" }]);
people.add([{ name: "joe3" }]);
people.add([{ name: "joe4" }]);
people.add([{ name: "joe5" }]);

people.remove([{ name: "joe3" }]);



console.log(people.toJSON());

5 个答案:

答案 0 :(得分:36)

对于其他寻找删除位置的人,您只需使用collection.where调用链接即可。像这样删除与搜索匹配的所有项目:

people.remove(people.where({name: "joe3"}));

请参阅Backbone collection.where

答案 1 :(得分:34)

通过做:

people.remove([{ name: "joe3" }]);

您不删除模型,因为您只传递了一个未连接到people集合的普通对象。相反,你可以做这样的事情:

people.remove(people.at(2));

或者:

var model = new Person({name: "joe3"});
people.add(model);
...
people.remove(model);

也可以。

所以你需要从集合中引用实际的模型对象;

http://jsfiddle.net/kD9Xu/

答案 2 :(得分:5)

var Person = Backbone.Model.extend({
    defaults: {
        name: "underfined",
        age:"underfined"
    }
});

var People = Backbone.Collection.extend({
    initialize: function () {
        this.bind('remove', this.onModelRemoved, this);
    },
    model: Person,
    onModelRemoved: function (model, collection, options) {
        alert("removed");
    },
    getByName: function(name){
       return this.filter(function(val) {
          return val.get("name") === name;
        })
    }
});

var people = new People();

people.add(new Person({name:"joe1"}));
people.add(new Person({name:"joe2"}));
people.remove(people.getByName("joe1"));

console.info(people.toJSON());

答案 3 :(得分:4)

另一种方法是缩短一点,并为集合触发删除事件:

people.at(2).destroy();
// OR
people.where({name: "joe2"})[0].destroy();
  

触发"销毁"模型上的事件,它会冒出任何包含它的集合。http://backbonejs.org/#Model-destroy

答案 4 :(得分:0)

要删除“[0]”,您可以使用以下代码:

people.findWhere({name: "joe2"}).destroy();