简体   繁体   中英

Working with nested views in Backbone.JS

I'm developing an app with Backbone.JS, consisting of a main view (IndexView) with a menu, an HTML5 video loop and a div for content (#container). The idea is that when the app is initialized, depending on the route, a view will be render and displayed on the #container element. Regardless of the route, the IndexView should always be shown. This is what I have:

router.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
};

views/index.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;
});

views/about.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;
});

Well, the problem is that the IndexView is rendered properly, but the other views are not. I suspect it is because, for some reason, they don't see the #container element created by the IndexView. I say this because if I have those views rendering to the body element instead, they do it just fine.

Any suggestions? Thanks in advance!

Your problem is that the statement assigning the el is evaluated to early (that is it is being evaluated when your view is being defined as opposed to when you create your actual view which is before your index view has been rendered. What you should do is either pass in the el when you instantiate the view or you can manually assign it in the initialize method of your view.

For example to pass in the el

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM