我不确定这个问题是否特定于 Backbone.js。我有一个具有以下渲染功能的模型:
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
的变量。这是因为在回调中,当我希望将它设置为 View 时,this
被设置为 window
。有没有一种方法可以保留 this
的原始引用而不将其存储在另一个变量中?
最佳答案
Is there a way I can retain the original reference of this without storing it in another variable?
是的,这是 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)
});
关于javascript - 在回调函数中保留 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18604875/