更新/销毁我的观点,我相信我的逻辑可能需要注意

Updating/Destroying my Views, I believe my logic may need attention

本文关键字:我的 我相信 观点 更新      更新时间:2023-09-26

我有一个骨干项目,可以从真实的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();

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

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)
},