首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >移除集合中的模型并触发移除事件- backbone.js

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

Stack Overflow用户
提问于 2013-02-25 21:24:49
回答 4查看 54.3K关注 0票数 18

如何移除集合中的模型并激发移除事件。我试过people.remove([{ name: "joe3" }]);,但它不起作用。

代码语言:javascript
复制
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());
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-02-25 21:56:16

通过执行以下操作:

代码语言:javascript
复制
people.remove([{ name: "joe3" }]);

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

代码语言:javascript
复制
people.remove(people.at(2));

或者:

代码语言:javascript
复制
var model = new Person({name: "joe3"});
people.add(model);
...
people.remove(model);

同样也会起作用。

因此,您需要引用集合中的实际模型对象;

http://jsfiddle.net/kD9Xu/

票数 37
EN

Stack Overflow用户

发布于 2014-10-01 14:04:43

对于其他正在寻找remove where的人,只需使用collection.where调用将其链接即可。如下所示,删除与搜索匹配的所有项目:

代码语言:javascript
复制
people.remove(people.where({name: "joe3"}));

请参阅Backbone collection.where

票数 38
EN

Stack Overflow用户

发布于 2013-02-25 22:11:15

代码语言:javascript
复制
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());
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15068036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档