AwkwardCoder
AwkwardCoder

Reputation: 25651

backbone view not being shown when page first rendered

I have the following set of Views and Router, when the page is first displayed the 'welcome' view navigated too in the 'initialize' method for the Router is not visible - the render method is called but the element is not updated. If navigate to another view (hashbang) and then navigate back I can then see the initial view.

Does anyone know what I'm doing wrong?

 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();

The View is shown below:

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);
        }
    }),

Upvotes: 1

Views: 1065

Answers (1)

timDunham
timDunham

Reputation: 3318

Seems like a $(document).ready issue to me. Are you sure all the content of your page (specifically #content-pane) is loaded before you create the view?

Upvotes: 1

Related Questions