如何移除集合中的模型并激发移除事件。我试过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());
发布于 2013-02-25 21:56:16
通过执行以下操作:
people.remove([{ name: "joe3" }]);
您不能删除模型,因为您只传递了一个没有连接到people
集合的普通对象。相反,您可以这样做:
people.remove(people.at(2));
或者:
var model = new Person({name: "joe3"});
people.add(model);
...
people.remove(model);
同样也会起作用。
因此,您需要引用集合中的实际模型对象;
发布于 2014-10-01 14:04:43
对于其他正在寻找remove where的人,只需使用collection.where调用将其链接即可。如下所示,删除与搜索匹配的所有项目:
people.remove(people.where({name: "joe3"}));
发布于 2013-02-25 22:11:15
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());
https://stackoverflow.com/questions/15068036
复制相似问题