渲染子视图时,主干视图中不存在$(this.el)

no existant $(this.el) in backbone view while rendering child view

本文关键字:视图 不存在 this el      更新时间:2023-09-26

完整代码在这里…http://pastebin.com/EEnm8vi3

第378行没有将节插入当前视图。节模型被正确地传递到方法中。除了插入子渲染视图外,其他一切都按预期工作。

我想知道为什么$(this.el)是空的,因此不允许追加。尝试使用像$('#sections')这样的直接选择器也不起作用。

相关代码从上面的pastbin链接重复:(addOne方法)

SCC.Views.SectionView = Backbone.View.extend({
    tagName: "div",
    className: "section",
    initialize: function(){
        _.bindAll(this, 'render');
        this.template = _.template($('#section-tmpl').html());
    },
    render: function() {
        console.log($(this.el));
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});

SCC.Views.SectionsView = Backbone.View.extend({
    tagName: "div",
    id: "sections",
    className: "sections",
    initialize: function(){
        _.bindAll(this, 'render');
         //SCC.Sections.bind('add',   this.addOne, this);
         SCC.Sections.bind('reset', this.addAll, this);
         SCC.Sections.bind('all',   this.render, this);
    },
    render: function() {
        $(this.el).html("<p>rendered</p>");
        return this;
    },
    addOne: function(section) {
        var view = new SCC.Views.SectionView({model: section});
        $(this.el).append(view.render().el);
    },
    addAll: function() {
        this.collection.each(this.addOne);
    }
});

SCC.Sections = new SCC.Collections.Sections();
SCC.SectionsView = new SCC.Views.SectionsView({collection:SCC.Sections});
SCC.Sections.reset(window.SectionData);
$('#main').append(SCC.SectionsView.render().el);

我自己也遇到过这个问题,所以我把这个答案留给其他人:

当你绑定这个。渲染到"all",就像@lukemh做的那样:

SCC.Sections.bind('all', this.render, this);

你实际上是在说每次在模型/集合中触发事件时重新渲染视图。当你在render方法中使用.html()时,你还将通过addOne函数覆盖任何可能已经.append() ed到它的子视图。

如果你移动$(this.el).html()调用到初始化视图,问题就解决了。你仍然可以将render绑定到'all',但要确保你只重新渲染其中的一部分,否则你会再次覆盖子视图。