护"本"里面的回调函数 [英] Retaining "this" inside callback function

查看:108
本文介绍了护"本"里面的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道,如果这个问题是特定于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 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?

解决方案

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 method

this.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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆