如何检查侧栏视图是否已在骨干中呈现?

时间:2016-11-12 21:14:55

标签: javascript backbone.js backbone-views

通常,用户通过主页进入网站,然后在那里渲染侧边栏视图。接下来,用户单击链接,路由器将呈现另一个视图并替换原始内容视图。侧边栏视图不会重新渲染。

当用户在子页面上单击刷新时,不会呈现侧栏。

如何检查视图是否存在且已呈现?

1 个答案:

答案 0 :(得分:2)

分担责任并坚持下去。不要将侧边栏渲染放在主页视图的手中。

您可以使用布局视图来处理呈现内容标题页脚边栏。然后,当用户导航到另一个页面时,路由器只在布局视图上调用类似setContent(view)的内容,这样可以确保在呈现内容之前呈现侧边栏(以及其他所有内容)。

假设这个模板:

<body>
    <div class="header"></div>
    <div class="content"></div>
    <div class="sidebar"></div>
</body>

布局视图可以简单如下:

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 AppRouter = Backbone.Router.extend({
    routes: {
        '*otherwise': 'homepage',
        'specific/:id': 'specificPage'
    },
    initialize: function() {
        this.layout = new Layout();
        this.layout.render();
        this.views = {};
    },
    homepage: function() {
        // These local variables improve minification and readability.
        var views = this.views,
            homepage = views.homepage;
        if (!homepage) {
            views.homepage = homepage = new HomePage();
        }
        this.layout.setContent(homepage);
    },
    specificPage: function(id){
        var views = this.views,
            specific = views.specific;
        if (!specific){
            views.specific = specific = new HomePage();
        }
        specific.setId(id); // hypothetical logic
        this.layout.setContent(specific);
    }
});