Jeremy H.
Jeremy H.

Reputation: 523

Nested Backbone Views Not adding to the DOM

I am new to Backbone.js and having a difficult time getting nested views to display. The render method of the Login view fires, but nothing gets added to the DOM. It seems to be that it isn't seeing the elements from the parent view.

elm.views.Navigation = Backbone.View.extend({

    render: function () {
        this.$el.html(this.template());
        new elm.views.Login({model: this.model, el: '#login'});
        return this;
    },

    events: {
        'mousedown li': 'mouseDown',
        'mouseup li': 'mouseUp',
        'click .btn-login': 'login'
    },

    mouseDown: function (e) {
        $(e.currentTarget).addClass('active');
    },

    mouseUp: function () {
        $('li').removeClass('active');
    },

    login: function () {
        $(document).trigger('login');
        return false;
    }

});

elm.views.Login = Backbone.View.extend({

    initialize: function() {
        this.render();
    },

    render: function () {
        console.log("login render");
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },

    events: {
        'click .login': 'login',
        'click .logout': 'logout'
    },

    login: function (e) {
        $(document).trigger('login');
        return false;
    },

    logout: function (e) {
        $(document).trigger('logout');
        return false;
    }

});

In Response to Comments:

The navigation view is being shown from within the initializer of the router:

initialize: function() {        
    elm.user = new elm.models.Person();
    elm.navigationView = new elm.views.Navigation({model: elm.user});
    $("#pageContent").html(elm.navigationView.render().el);
},

Upvotes: 0

Views: 73

Answers (1)

nikoshr
nikoshr

Reputation: 33344

Your navigation view works on a detached DOM node, which means that #login can not be found by your login view and thus can't be filled.

Either pass your container as an el argument to your main view:

elm.navigationView = new elm.views.Navigation({
    model: elm.user, 
    el: "#pageContent"
});
navigationView.render();

http://jsfiddle.net/nikoshr/L1wp4vds/ for a demo

or scope your sub element to the element used in your main view:

elm.views.Navigation = Backbone.View.extend({
    render: function () {
        this.$el.html(this.template());
        new elm.views.Login({el: this.$('#login')});
        return this;
    }

    ...
});

http://jsfiddle.net/nikoshr/L1wp4vds/1/

Upvotes: 2

Related Questions