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

时间:2012-08-14 11:49:38

标签: javascript backbone.js underscore.js

我有一个骨干项目,从许多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();

1 个答案:

答案 0 :(得分:2)

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

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