javascript - 如何确保我总是在 View 上调用删除?

标签 javascript backbone.js

我在页面上有一个区域,假设由以下位置给出:

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

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

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

处理这种情况的最佳模式是什么?我是否应该跟踪应用程序代码中某些内容的“事件” View 并对其调用 remove

即我的应用程序有这样的内容:

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

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

app.regions.regions1.currentView.remove() 

最佳答案

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

这是一个简单的布局 View ,取自 another answer of mine 。看一下 setContent,其中 View 与新 View 交换,并且在旧 View 上调用 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

关于javascript - 如何确保我总是在 View 上调用删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41599762/

相关文章:

backbone.js - 如何在 "mustache"中(如underscore.js)进行if/then?

javascript - ElementsFromPoints 不适用于 ResizeObserver

javascript - 为什么我不能创建一个 Backbone.Collection of Backbone.Views?

backbone.js - 在方法中从 Backbone.Model 获取默认值?

javascript - 在 Cloud Firestore 中返回文档

backbone.js - 渲染字段时Wtforms转义包含自变量js模板的value参数

类似于 Backbone.js 的 javascript 继承

asp.net - 使用 TinyMCE 进行 HTML 编码

javascript - 如何使 onblur 事件不在特殊 div 中工作

php - 网站翻译onload