How to access 'this' inside a callback function in Typescript?

Tristan C picture Tristan C · Nov 1, 2016 · Viewed 14.6k times · Source

I am trying to set a variable declared at the beginning of the class (a boolean) to true once a callback is called, but I keep getting a TypeScript erorr.

Here is the error:

TypeError: Cannot set property 'nonReceived' of undefined

Here is my code:

  finalizeToken(){
  braintree.setup(JSON.parse(this.finalToken), 'dropin', {
     container: 'dropin-container',
     defaultFirst: true,
      form: 'checkout-form',
      onPaymentMethodReceived: function (obj) {
        this.nonReceived = true;
      localStorage.setItem('nonce', obj.nonce);
    }
  });  
}

The brintree-setup connect to Braintree Payments, and awaits user payment info. Once they submit the form, I need the variable "this.nonReceived" to be set to true.

Answer

Konstantin Vitkovsky picture Konstantin Vitkovsky · Nov 1, 2016

If you use ES5 syntax you could use function(){}.bind(this) to bind the callback with the context but with Typescript you can use ES6 syntax and use arrow function (parameters) => {function_body} which bind current context implicitly.