嵌套的骨干视图不添加到DOM

时间:2015-02-24 23:05:54

标签: javascript templates backbone.js views

我是Backbone.js的新手,很难获得嵌套视图。触发Login视图的render方法,但不会向DOM添加任何内容。似乎它没有从父视图中看到元素。

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

});

回应评论:

导航视图正在路由器的初始化程序中显示:

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

1 个答案:

答案 0 :(得分:2)

您的导航视图适用于分离的DOM节点,这意味着您的登录视图无法找到#login,因此无法填充。

将容器作为el参数传递到主视图:

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

http://jsfiddle.net/nikoshr/L1wp4vds/演示

或将您的子元素范围限定为主视图中使用的元素:

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/