保留“这个"内部回调函数 [英] Retaining "this" inside callback function
问题描述
我不确定这个问题是否特定于 Backbone.js.我有一个具有以下渲染功能的模型:
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;
}
如您所见,在success
回调函数中,我使用了一个名为self
的变量.这是因为在回调内部,当我希望将 this
设置为视图时,它被设置为 window
.有没有办法可以保留 this
的原始引用而不将其存储在另一个变量中?
As you can see, inside the success
callback function, I use a variable called self
. This is because inside the callback, this
is set to window
when I want it to be set to the view. Is there a way I can retain the original reference of this
without storing it in another variable?
推荐答案
有没有办法可以保留 this 的原始引用而不将其存储在另一个变量中?
Is there a way I can retain the original reference of this without storing it in another variable?
是的,这是 proxy
方法的合理用例一个>
Yes, this is a reasonable use case for the proxy
method
this.model.fetch({
success: $.proxy(function() {
this.$el.append(this.template(this.model.attributes));
}, this)
});
<小时>
或者,您可以使用下划线的 bind
方法:
this.model.fetch({
success: _.bind(function() {
this.$el.append(this.template(this.model.attributes));
}, this)
});
这篇关于保留“这个"内部回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!