你有上下文問題。您提到的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);
}
完美,很好!非常感謝,我也會記住文檔流問題。確實非常有用的信息! –