Backbone.js的:从调用视图的初始化渲染()函数 [英] Backbone.js: calling render() from view's Initialize: function
问题描述
我想我的观点来表现自己当第一次创建它,所以我打电话 this.render();
在初始化:
功能,这样(有些code删除):
I want to my view to render itself when it is first created, so I am calling this.render();
in the initialize:
function, like this (some code removed):
var MyView = Backbone.View.extend({
el: $("#mydiv"),
initialize: function() {
this.render();
}
...
在渲染:
功能,我再通过子集合循环,并追加每个子元素的渲染视图:
In the render:
function I'm then looping through a child collection, and appending the rendered views of each child element:
render: function() {
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
this.el.append(view.render().el); //*****
});
return this;
},
我遇到的问题是,提及这个
在渲染功能(标有星号)设置为窗口
,而不是 MyView的
对象,而且它导致错误。
The problem I'm having is that that the reference to this
in the render function (marked with asterisks) is set to window
rather than the MyView
object, and it's causing an error.
我假设我打电话渲染不正确(目前 this.render();
)。我应该怎么做这个,使这个
上下文是preserved?
I assume I am calling render incorrectly (currently this.render();
). How should I be doing this so that the this
context is preserved?
推荐答案
保存这个
之外的for循环。
Save this
outside the for loop.
var that = this;
这个
如果你使用 _不循环内传输。每个()
。
这篇关于Backbone.js的:从调用视图的初始化渲染()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!