-1

我有一个骨干项目,可以从各种 API 中提取播客。

我要解决的问题是删除当前显示的所有视图。我想通过将事件绑定到单击“删除”锚点时触发的每个视图来做到这一点。

目前,集合重置触发并删除所有模型,但我无法确保视图也被销毁。我想我的逻辑需要帮助。

这是我的代码:

podSearch = Backbone.Model.extend();
podSearchCollection = Backbone.Collection.extend({
    model: podSearch,
    parse: function(response) {
        return response.results;
    }
});

ownerList = Backbone.Model.extend();
ownerListCollection = Backbone.Collection.extend({
    model: ownerList,
    parse: function(response) {
        return response.results;
    }
});

Search = Backbone.View.extend({
    initialize: function(){
        this.searchCollection = new podSearchCollection();
        this.searchCollection.bind('reset', this.appendResult, this);
    },
    events: {
        "click button" : "getTerm"
    },
    doSearch: function(term){
        /* get term and collection url */
        this.searchCollection.fetch();
    },
    appendResult: function(){
        _.each(this.searchCollection.models, function (item) {
            var listItem = new ownerItem({model:item});
            $('#results').append(listItem.render().el);
        });
    },
    removeAll: function(){
        console.log(this.searchCollection);
        this.searchCollection.reset();
    }
});

ownerItem = Backbone.View.extend({
    template: $("#castOwner").html(),

    initialize: function(){
        this.ownerListCollection = new ownerListCollection();
        this.ownerListCollection.bind('reset', this.appendResult, this);
        this.model.bind("reset", this.removeSelf);
    },
    render: function(){
        var tmpl = _.template(this.template);
        this.$el.html( tmpl( this.model.toJSON() ) );
        return this;
    },
    events: {
        "click a" : "pullCasts",
        "click a.removeAll" : "removeAll"
    },
    pullCasts: function(e){
        e.preventDefault();
        var id = this.$el.find('a').attr("href");
        this.ownerListCollection.url = 'http://itunes.apple.com/lookup?id=' + id + '&entity=podcast&callback=?';
        this.ownerListCollection.fetch();
    },
    appendResult: function(){
        _.each(this.ownerListCollection.models, function(item){
            /* do something with each item */
        }, this);
        $(this.el).append('<p><a href="#" class="removeAll">Remove All</a></p>');
    },
    removeAll: function(){
        search.removeAll();
    },
    removeSelf: function(){
        console.log("rm");
    }
});

search = new Search();
4

1 回答 1

2

为了在模型被销毁时删除视图,您可以向视图添加一个侦听器,如果模型被销毁,它将删除视图:-

initialize: function () {
    //view gets re-rendered if model is changed
    this.model.on("change", this.render, this);
    //view gets removed if model is destroyed
    this.model.on("destroy", this.remove, this)
},
于 2012-08-14T12:54:46.993 回答