为什么这个主干视图无法正确呈现?

Ste*_*evo 1 backbone.js

我在backbone.js中有一些观点,我想要成为另一个的孩子.所以我创建了以下代码.

var app = app || {} ;

app.ProjectCardView = Backbone.View.extend({

    el: $('.list'),

    template: _.template( $("#tpl-project-card-summary").html() ),


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

    render: function() {
        return this.$el.html( this.template() );

    }

});


app.DashboardView = Backbone.View.extend({

    el: $('.contentwrap'),

    template: _.template( $("#tpl-dashboard").html() ),

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

    render: function() {
        //console.log(this.template());
         this.$el.html( this.template() );

    },

    addProjects: function() {
        var pcv = new app.ProjectCardView();    
    }



});

app.dash = new app.DashboardView;
Run Code Online (Sandbox Code Playgroud)

DashboardView渲染完美,但是当我创建ProjectCardView时,视图似乎没有初始化,因此模板为空并且未设置el.如果我在初始化函数中设置el,则仍然没有设置$ el.我只是看不出我做错了什么.

编辑:看起来我发现了这个问题; $('.list')是第一个视图引入的元素,因此,即使第一个视图已在DOM中呈现,它也不会在第二个视图尝试找到它时呈现.

那么我该如何解决这个问题呢?

nem*_*esv 5

如果将el指定为jQuery选择器$('.list'),则应该知道它将在执行时Backbone.View.extend执行.因此,如果您的元素不在DOM中,那么您的选择器将无法工作.

所以你需要指定el它在DOM中的时间.所以在你的情况下你可以写:

addProjects: function() {
    var pcv = new app.ProjectCardView({ el: $('.list') });    
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用Backbone功能,您可以将其指定el为字符串而不是jQuery选择器:

app.ProjectCardView = Backbone.View.extend({    
    el: '.list',
    //...
}
Run Code Online (Sandbox Code Playgroud)