18

如何删除删除集合中的模型并使删除事件触发。我试过 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());
4

5 回答 5

38

对于其他寻找删除位置的人,您可以简单地使用 collection.where 调用将其链接起来。像这样删除与搜索匹配的所有项目:

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

骨干collection.where

于 2014-10-01T06:04:43.360 回答
37

通过做:

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/

于 2013-02-25T13:56:15.857 回答
5

另一种方法更短一些,并且也会触发集合的remove事件:

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

在模型上触发“销毁”事件,该事件将通过包含它的任何集合冒泡。http://backbonejs.org/#Model-destroy

于 2015-04-27T14:18:47.367 回答
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());
于 2013-02-25T14:11:14.590 回答
0

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

people.findWhere({name: "joe2"}).destroy();
于 2016-01-02T15:31:44.747 回答