在 Backbone.JS 中使用嵌套视图

Working with nested views in Backbone.JS

本文关键字:嵌套 视图 Backbone JS      更新时间:2023-09-26

我正在开发一个带有Backbone.JS的应用程序,它由一个带有菜单的主视图(IndexView)、一个HTML5视频循环和一个用于内容的div(#container)组成。这个想法是,当应用初始化时,根据路由,视图将呈现并显示在 #container 元素上。无论路由如何,都应始终显示索引视图。这是我所拥有的:

路由器.js:

var initialize = function () {
    // The IndexView will be rendered when the app is initialized
    console.log("Rendering index view...");
    var indexView = new IndexView();
    indexView.render();
    var app_router = new AppRouter;
    // One of the routes
    app_router.on('route:about', function () {
        var aboutView = new AboutView();
        aboutView.render(); 
    });
    // Other routes here…
    Backbone.history.start();
};
return {
    initialize: initialize
};

视图/索引.js:

define([
    'jquery',
    'underscore',
    'backbone',
    'text!templates/index.html'
], function ($, _, Backbone, indexTemplate) {
    var IndexView = Backbone.View.extend({
        el : $("body"),
        render : function () {
            var data = {};
            var compiledTemplate = _.template(indexTemplate, data);
            this.$el.html(compiledTemplate);
        }
    }); 
    return IndexView;
});

视图/关于.js:

define([
    'jquery',
    'underscore',
    'backbone',
    'text!templates/about.html'
], function ($, _, Backbone, aboutTemplate) {
    var AboutView = Backbone.View.extend({
        el : $("#container"),
        render : function () {
            var data = {};
            var compiledTemplate = _.template(aboutTemplate, data);
            this.$el.html(compiledTemplate);
        }
    }); 
    return AboutView;
});

好吧,问题是索引视图呈现正确,但其他视图没有。我怀疑这是因为,出于某种原因,他们看不到 IndexView 创建的 #container 元素。我这样说是因为如果我将这些视图呈现到 body 元素,它们就可以了。

有什么建议吗?提前感谢!

您的问题是分配el的语句被评估为 early(也就是说,在定义视图时对其进行评估,而不是在创建实际视图时(即在呈现索引视图之前)。您应该做的是在实例化视图时传入el,也可以在视图的初始化方法中手动分配它。

例如,传入el

var myAboutView = new AboutView({el: $('#container')};