如何确保我总是在视图上调用删除?

How to be sure I always call remove on a view?

我在页面上有一个区域,比方说:

<div id="region1"></div>
<div id="region2"></div>

我在应用程序中有多个视图。在任何时候,它们中的任何一个都可能被渲染成#region1。然后,渲染另一个。

我不想只调用 $('#region1').html('') 来从应用程序区域的最后一个视图中删除 html。我想在被丢弃的视图上调用 .remove()。但是不知道是哪一个

处理这种情况的最佳模式是什么?我应该在我的应用程序代码中跟踪 "active" 视图并调用 remove 吗?

即我的申请是这样的:

//update this every time a view is rendered into region1
app.regions.region1.currentView = viewA ;

然后当我将另一个视图渲染到 region1 时,我首先调用:

app.regions.regions1.currentView.remove() 

共享 div 并跟踪正在呈现的视图的一种方法是使用视图管理应用程序布局。

这是取自 another answer of mine 的简单布局视图。看看 setContent 视图与新视图交换的位置,如果有的话,remove 会调用旧视图。

var Layout = Backbone.View.extend({
    el: 'body' // just for the simple example, let's put this as the body.

    // This avoids repeating selector strings everywhere in the view code.
    // If you change a class name in the template, change it only once here.
    regions: {
        header: '.header',
        content: '.content',
        sidebar: '.sidebar'
    },
    initialize: function(options) {
        var regions = this.regions;

        // I like to "namespace" my sub-views into an object.
        // That way, you still can access them by name, but you can also
        // loop on the sub-views.
        this.views = {
            sidebar: new SideBar({ el: regions.sidebar }),
            header: new Header({ el: regions.header }),
        };

        this.$content = this.$(regions.content);
    },

    render: function() {
        _.invoke(this.views, 'render');
        return this;
    },

    /**
     * Set the content to a view.
     * @param {Backbone.View} view to replace the content with.
     */
    setContent: function(view) {
        var views = this.views,
            content = views.content;
        if (content !== view) {
            if (content) content.remove();
            views.content = content = view;
            this.$content.html(content.render().el);
        }
    },
});

然后使用它:

var layout = new Layout(),
    homepage = new HomePage();
layout.render()
    .setContent(homepage);

// ...later, changing the content view
layout.setContent(newView); // as simple as this