2016-05-29 6 views
0

私はいくつかの時間intantiatedクラスを持っています。コールバックで "this"をどう扱うか?

Captcha = function(el) { 
    var _this = this; 
    this.el = $(el); 
    this.button = this.el.parent().find('button'); 
    this.render(); 
}; 


Captcha.prototype.callback = function() { 
    _this.el.addClass('visuallyhidden'); 
    _this.button.removeClass('visuallyhidden'); 
}; 

Captcha.prototype.render = function(grecaptcha){ 
    this.grecaptcha.render(this.el.dom[0],{ 
     'sitekey' : 'hash', 
     'callback': this.callback 
    }); 
}; 

this.callbackは、api-requestでコールバックとしてトリガされる関数を参照します。ご覧のとおり、私はこの関数を参照するために_thisを使用しようとしますが、何らかの理由でコールバック内で利用できません。

+1

はあなたの_thisグローバル –

+3

はthis.callback.bind(この) 'S.Petrosov @ – dandavis

+0

は、私はクラスとコールバックの複数のインスタンスを持つbecuaseすることはできません'と 'this.callback'を交換しますそれがどれであるかを知る必要があります。 – Himmators

答えて

0

windowオブジェクトには常にクイックストレージとしてオブジェクトを追加できます。

Captcha = function(el) { 
    var _this = this; 
    window.captchaObject = this; 
    this.el = $(el); 
    this.button = this.el.parent().find('button'); 
    this.render(); 
}; 

Captcha.prototype.callback = function() { 
    var _this = window.captchaObject; 
    _this.el.addClass('visuallyhidden'); 
    _this.button.removeClass('visuallyhidden'); 
}; 

Captcha.prototype.render = function(grecaptcha){ 
    this.grecaptcha.render(this.el.dom[0],{ 
     'sitekey' : 'hash', 
     'callback': this.callback 
    }); 
}; 
+1

私はクラスのインスタンスが複数あり、コールバックがそれを知る必要があるので、私はできません。 – Himmators

関連する問題