Javascript 删除集合中的模型并触发删除事件-backbone.js
如何删除集合中的模型并触发删除事件。我尝试了Javascript 删除集合中的模型并触发删除事件-backbone.js,javascript,backbone.js,Javascript,Backbone.js,如何删除集合中的模型并触发删除事件。我尝试了people.remove([{name:“joe3”}])但它不起作用 var Person = Backbone.Model.extend({ initialize: function () { console.log(" person is initialized"); }, defaults: { name: "underfined", age:"underfined"
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());
通过这样做:
people.remove([{ name: "joe3" }]);
您不会删除模型,因为您只传递一个未连接到人员
集合的普通对象。相反,您可以这样做:
people.remove(people.at(2));
或:
这也行
因此,您需要引用集合中的实际模型对象
对于其他任何想要删除where的人,您只需将其与collection.where调用链接即可。如要删除与搜索匹配的所有项目,请执行以下操作:
people.remove(people.where({name: "joe3"}));
请参见另一种方法稍微短一点,并为集合触发移除事件:
people.at(2).destroy();
// OR
people.where({name: "joe2"})[0].destroy();
在模型上触发一个“销毁”事件,该事件将在包含它的任何集合中冒泡出现
要删除“[0]”,可以使用以下代码:
people.findWhere({name: "joe2"}).destroy();
thnaks-请再问一个问题-如何在删除的函数中获取模型属性的值:onModelRemoved:function(model,collection,options){console.log(“options=”,options);alert(“删除的”+model.attributes.name+“+model.attributes.age+”已删除”),我有一个相关的问题:Backbone.Model的pop
方法是否触发删除事件?(它似乎不…@Ziggy是的,当然。集合的pop
方法将从集合中删除模型并触发remove
事件,除非使用silent
选项将其抑制。那么为什么不删除ByName()呢?这似乎也是我要找的。简单、直截了当的答案。
people.at(2).destroy();
// OR
people.where({name: "joe2"})[0].destroy();
people.findWhere({name: "joe2"}).destroy();