2011-08-15 248 views
1

全码... 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); 
+0

尝试将addOne和addAll添加到_.bindAll(this,...)函数中。我想为什么它可能会失败,因为addAll的“this”不是BackboneView,除非你已经绑定了它。 – Bartek

+0

我认为这样做!!!!!也摆脱了'$(this.el).html(“

呈现

”); '我认为有帮助? – lukemh

+0

而不是写'$(this.el)',这意味着你多次将元素转换为jQuery,你应该使用'this。$ el'。为了方便和高效,它被内置到Backbone中。 – Micros

回答

2

我就遇到了这个问题,我自己,所以我会离开这个答案的任何人在那里:

当你绑定this.render为“所有”作为@lukemh那样:

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

你实际上是说每次的事件模型/收集触发重新渲染视图。当您使用的.html()呈现方法你也将可以覆盖已经.append任何儿童的意见()“编吧throught的addOne功能。

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