Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 619
Tristan C Avatar asked Nov 01 '16 02:11

Tristan C


People also ask

How do I return a value from a callback in TypeScript?

Just change the function call to const result = await Service. doCallAuth("test", "test") , Promises handle async/await pattern, and wrap the await call by try/catch pattern to catch errors.

How do you pass a callback function in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

How do you read a callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.


1 Answers

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.

like image 115
Konstantin Vitkovsky Avatar answered Sep 18 '22 05:09

Konstantin Vitkovsky