护"本"里面的回调函数 [英] Retaining "this" inside callback function
问题描述
我不知道,如果这个问题是特定于Backbone.js的。我有一个模型以下渲染功能:
渲染:功能(){
VAR自我=这一点;
这$ el.empty();
this.model.fetch({
成功:函数(){
自$ el.append(self.template(self.model.attributes));
}
}); 返回此;
}
正如你所看到的,成功在
的回调函数,我使用了一个叫做变量自
。这是因为回调里面,将此
设置为窗口
时,我希望它被设置为视图。有没有一种方法可以让我保留这个
的原始参照,而不将它存储在另一个变量?
有没有一种方法,我可以保留原来这个基准,而不将它存储在另一个变量?
块引用>是的,这是一个合理的用例
代理
方法this.model.fetch({
成功:$ .proxy(函数(){
这$ el.append(this.template(this.model.attributes));
}, 这个)
});另外,您可以使用下划线的
绑定
方法:this.model.fetch({
成功:_.bind(函数(){
这$ el.append(this.template(this.model.attributes));
}, 这个)
});I'm not sure if this question is specific to Backbone.js. I have a model with the following render function:
render: function() { var self = this; this.$el.empty(); this.model.fetch({ success: function() { self.$el.append(self.template(self.model.attributes)); } }); return this; }
As you can see, inside the
success
callback function, I use a variable calledself
. This is because inside the callback,this
is set towindow
when I want it to be set to the view. Is there a way I can retain the original reference ofthis
without storing it in another variable?解决方案Is there a way I can retain the original reference of this without storing it in another variable?
Yes, this is a reasonable use case for the
proxy
methodthis.model.fetch({ success: $.proxy(function() { this.$el.append(this.template(this.model.attributes)); }, this) });
Alternatively you can use underscore's
bind
method:this.model.fetch({ success: _.bind(function() { this.$el.append(this.template(this.model.attributes)); }, this) });
这篇关于护"本"里面的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!