2013-05-18 56 views
5

我一直在玩骨干,并试图学习它。我在这一点上停留了一段时间。无法弄清楚下面的代码有什么问题?为什么这个渲染函数不起作用?

render: function() { 
    this.$el.empty(); 
    // render each subview, appending to our root element 
    _.each(this._views, function(sub_view) { 
     this.$el.append(sub_view.render().el); // Error on this line 
    }); 

回答

11

你有上下文问题。您提到的this不包含您正在寻找的$el。您可以通过声明self变量来指出适当的this来解决此问题。以下代码应该适合你。

render: function() { 
    var self = this; //Added this line to declare variable (self) that point to 'this' 
    this.$el.empty(); 
    _.each(this._views, function(sub_view) { 
     self.$el.append(sub_view.render().el); //Used 'self' here instead 'this' 
}); 

侧面说明:当你靠在骨干也应该知道一个非常commong JavaScript的问题文件的回流。您正在渲染集合中每个单一模型的视图。它可能会导致性能问题,特别是在旧电脑和移动设备上。您可以通过渲染container中的所有内容并追加一次优化代码,而不是每次更新DOM。这里是一个例子:

render: function() { 
    this.$el.empty(); 
    var container = document.createDocumentFragment(); 
    _.each(this._views, function(sub_view) { 
    container.appendChild(sub_view.render().el) 
    }); 
    this.$el.append(container); 
} 
+0

完美,很好!非常感谢,我也会记住文档流问题。确实非常有用的信息! –

相关问题