javascript - 在回调函数中保留 "this"

标签 javascript jquery html backbone.js

我不确定这个问题是否特定于 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/

相关文章:

javascript - 发送同步 Ajax 请求时显示微调器

javascript - js变量在ajax中不更新

jquery - Django:将 HTML 字符串传递给模板

JavaScript : Use of closure variable

html - 高度与其他列相同的列

javascript - NullInjectorError : No provider for Overlay! NgxToastr

javascript - 如何绑定(bind)到 jQuery 中文本区域的更改事件?

jquery - IE8 :Image disappearing while rotating using jQuery Rotate

asp.net - JavaScript拼图: window. confirm = divConfirm(strMessage)

javascript - Tizen 可穿戴设备 - tizen.time.getCurrentDateTime() 与 new Date()