如何删除fetch上的item-view?

时间:2012-07-26 09:15:49

标签: javascript events backbone.js

我有一个UserCollection,由UsersView(列表)处理。单个元素,模型,作为UserView处理。

当我现在获取一个新的UserCollection(其他url)而不是集合对象本身的更新(包含新用户模型)但html列表仍然存在。

的ListView:

    var ContactsView = Backbone.View.extend({
        tagName: "ul",
        className: "contacts unstyled",
        events: {

        },
        initialize: function() {
            this.collection = new UserCollection();
            this.collection.bind('add', this.addContact, this);
            this.collection.bind('remove', this.removeContact, this); // not getting called
            this.collection.bind('reset', this.listContacts, this);
            this.collection.fetch();
        },
        render: function() {
            this.$el.html();

            return this;
        },
        listContacts: function(contacts) {
            contacts.each(function(contact) {
                this.$el.append(new ContactView({ model: contact }).render().el);
            }.bind(this));
        },
        addContact: function(contact) {
            this.$el.append(new ContactView({ model: contact }).render().el);
        },
        // this is not getting executed
        removeContact: function(contact) {
            console.log(["removeContact fired"]);
            contact.unset();
        }
    });

项 - 视图

    var ContactView = Backbone.View.extend({
        tagName: "li",
        className: "contact",
        template: _.template(ContactTemplate),
        events: {
            "mouseenter li.contact": "expandOptions"
            , "mouseleave li.contact": "collapseOptions"
            , "click": "removeContact"
        },
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('remove', this.remove, this);
            this.model.bind('destroy', this.remove, this);
            this.model.bind('unset', this.remove, this);
        },
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));

            return this;
        },
        expandOptions: function() {

        },
        collapseOptions: function() {

        },
        removeContact: function(e) {
            this.model.destroy();
        }
    });

当Backbone.Collection在内部删除项目(例如fetch)时会触发哪个事件,以及如何监听它?

1 个答案:

答案 0 :(得分:1)

收集提取时,the model data returns from the server收集会调用reset()并触发reset事件。

在您的reset绑定中,您必须清空()您的DOM元素。在你的情况下listContacts()