骨干视图未正确关闭

时间:2014-07-28 15:56:52

标签: javascript backbone.js

我一直在Chrome的开发工具中检查我的应用程序,我注意到openRace启动时有一些Detached DOM树元素。似乎正在发生的是它正在更新URL并创建新视图而不删除/销毁当前的PageView。

我目前在main.js中省略了this.remove()因为我想保留#content元素以供其他视图附加。

单击PageView中的.card元素后,您将进入新页面,但在控制台中,我收到有关GET localhost的错误:8000 / api-scrapers / data / race-index-RACE.json 404(找不到文件)告诉我仍有事件试图触发上一个视图。

main.js

require([
'app',

], function(App){

Backbone.View.prototype.close = function() {
    console.log("close called")
    if (this.onClose) {
        this.onClose();
    }
    this.undelegateEvents();
    this.off();
};

App.init();

});

pageView.js

var PageView = Backbone.View.extend({

        el: '#content',
        template: _.template(stateTemplate),

        events: {
            'click .card' : 'openRace'
        },

        initialize: function() {

            this.collection = new CollectionRacesState([]);
            this.listenTo(this.collection, 'reset', this.renderView);
            this.children = [];
            this.updateCollection()

        },

        updateCollection: function() {
            // console.log("updating collection...")
            var url = this.helper.getURL()
            this.collection.url = this.settings.get("defaultUrl") + 'race-index-' + (url[0]).toUpperCase() +'.json'
            this.collection.fetch({
                async: false,
                reset: true
            })
            // console.log(this.collection)
        },

        close: function() {

            console.log("closing PageState")

            // destroys children!!!
            _.each(this.views, function(view){
                view.undelegateEvents();
                view.remove();
                view.off();
            })

        },

        openRace: function(e) {
            console.log("opening race")

            var filename = $(e.currentTarget).attr("data-filename")
            Backbone.history.navigate("#/race/" + filename);

            this.close()
        },

    });

    return PageView

});

1 个答案:

答案 0 :(得分:0)

如果问题是保留'#content',请不要将el添加到PageView,同时渲染渲染并将视图el添加到此#content

var pageView = new PageView();
pageView.render();
pageView.$el.appendTo($('#content'));

通过此删除不会删除#content元素,并可用于其他视图。我通常会出于同样的原因避免使用el

相关问题