0

I have a class that is intantiated several times.

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 references a function that is triggered as a callback on an api-request. As you can see, I try to use _this to reference the function, but _this is not available inside the callback for some reason.

Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

0

You can always add objects to the window object as a quick storage.

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
    });
};
Mark
  • 3,224
  • 2
  • 22
  • 30