2013-05-18 59 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

完美,很好!非常感謝,我也會記住文檔流問題。確實非常有用的信息! –

相關問題