首次呈现页面时未显示主干视图

时间:2011-12-18 20:14:57

标签: javascript backbone.js

我有以下一组视图和路由器,当页面首次显示时,在'initialize'方法中导航的'welcome'视图也不可见 - 调用render方法但是元素没有更新。如果导航到另一个视图(hashbang),然后导航回来,我可以看到初始视图。

有谁知道我做错了什么?

 var AppRouter = Backbone.Router.extend({

        contentView: null,

        routes: {
            'welcome': 'welcomeAction',
            'settings': 'settingsAction',
            'books': 'booksAction',
            'book/:id': 'bookAction'
        },

        initialize: function () {
            this.navigate('welcome', true);
        },

        welcomeAction: function () {
            this.contentView = new views.WelcomeView({ 'model': new models.Welcome() });
        },

        settingsAction: function () {
            this.contentView = new views.SettingsView({ 'model': new models.Settings() });
        },

        booksAction: function () {
            this.contentView = new views.BooksView({ 'model': new models.Books() });
        },

        bookAction: function (id) {
            this.contentView = new views.BookView({ 'model': new models.Book({ 'Id': id }) });
        }
    });

    function App() {

        this.router = null;

        this.initialize = function () {
            this.router = new AppRouter;
            Backbone.history.start();
        };
    };

    var reader = new App;
    reader.initialize();

视图如下所示:

WelcomeView: Backbone.View.extend({

        'el': '#content-pane',

        tagName: 'div',

        template: _.template(templates.welcome),

        events: {
        },

        initialize: function () {
            _.bindAll(this, 'render');
            this.renderLoading();
            this.model.fetch({ success: _.bind(function () {
                this.model.set({ Date: new Date() });
                this.render();
            }, this)
            });
        },

        renderLoading: function () {
            var html = _.template(templates.loading)();
            $(this.el).empty();
            $(this.el).append(html);
        },

        render: function () {
            var html = this.template({ date: this.model.get('Date') });
            $(this.el).empty();
            $(this.el).append(html);
        }
    }),

1 个答案:

答案 0 :(得分:1)

对我来说似乎是一个$(document).ready问题。在创建视图之前,您确定已加载页面的所有内容(特别是#content-pane)吗?