你有上下文问题。您提到的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);
}
完美,很好!非常感谢,我也会记住文档流问题。确实非常有用的信息! –