Javascript Backbone.js:从视图调用render()';s初始化:函数
我希望我的视图在第一次创建时呈现自身,因此我调用Javascript Backbone.js:从视图调用render()';s初始化:函数,javascript,backbone.js,Javascript,Backbone.js,我希望我的视图在第一次创建时呈现自身,因此我调用this.render(),如下所示(一些代码已删除): 在render:函数中,我将循环遍历一个子集合,并附加每个子元素的渲染视图: render: function() { this.model.somecollection.forEach(function(c) { var view = new ChildView({ model: c }); this.el.append(view.render().
this.render()在初始化:
函数中的code>,如下所示(一些代码已删除):
在render:
函数中,我将循环遍历一个子集合,并附加每个子元素的渲染视图:
render: function() {
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
this.el.append(view.render().el); //*****
});
return this;
},
我遇到的问题是,渲染函数(用星号标记)中对this
的引用被设置为window
,而不是MyView
对象,这导致了一个错误
我假设我调用render的方式不正确(当前this.render();
)。我应该如何做才能保留这个上下文?这就是我们在这里使用它的方式
这样,在初始化时仍会调用渲染
ContactView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
// we use underscsore templating, this just gives a chunk of html
var template = _.template( $("#search_template").html(), {} );
// and we load that template html into the Backbone "el"
this.el.html( template );
}
});
当我们创建视图时,我们将“el”赋予视图,
渲染函数将html插入到该元素中
var contact_view = new ContactView({ el: $("#contact-list") });
将此保存到for循环外部
var that = this;
如果在Javascript中使用\ueach()
,则此
不会在循环中传输。每当您输入新函数上下文时,此
的值可能已更改。在输入函数之前,您只需存储此
的值:
render: function() {
var self = this;
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
self.el.append(view.render().el); //*****
});
return this;
},
在匿名函数的上下文中,这指的是全局范围。如果希望以编写代码的方式使用代码,则需要显式保留此内容。假设页面中有jquery:$。可以使用代理函数:
this.model.somecollection.forEach($.proxy)(函数(c){
var view=新的子视图({model:c})
this.el.append(view.render().el);
}这),;
或者,下划线有一个uz.bind函数,其工作方式类似。
此外,如果在匿名函数外部定义局部变量并将其分配给该变量,则可以在匿名函数内部使用该变量代替该变量 如果某个集合是主干。集合您应该能够说:
this.model.somecollection.each(…,this)代码>
最后一个参数是要在函数内部使用的上下文。将此安全设置为that
在for循环外部。@ZeissS-Doh!我真是太蠢了-把这个作为答案,我会接受的。谢谢。事实证明,我犯了一个愚蠢的错误(因为foreach/)而失去了这个上下文。但是很高兴看到另一种方法。Backbone.Collection.each()
为上下文使用第三个参数。Cobby的评论很重要。var=this代码>技巧有点像黑客,现在感觉有点粗糙。每个
实现都使用更好的来减少一些干扰。您还可以使用.bind()来设置此上下文的参数。
render: function() {
var self = this;
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
self.el.append(view.render().el); //*****
});
return this;
},
this.model.somecollection.forEach($.proxy(function(c) {
var view = new ChildView({ model: c });
this.el.append(view.render().el);
},this));