26

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.

Tristan C
  • 593
  • 2
  • 7
  • 16

1 Answers1

56

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.

Konstantin Vitkovsky
  • 1,198
  • 11
  • 15
  • 3
    Would the binding go onto where the function was called, or the function definition? – Tristan C Nov 01 '16 at 03:14
  • It helped , Thank you :) – Arash May 13 '18 at 14:08
  • Thanks. ES5 syntax worked for me inside ondrop for files drag and drop on a div. – Syed Nasir Abbas Jul 29 '20 at 16:45
  • This code may help someone: this.dndContainer.ondrop = function (e: any) { e.preventDefault(); e.stopPropagation() this.className = ""; var droppedFiles = e.dataTransfer.files; this.fileStore.push.apply(this.fileStore, droppedFiles); if (this.fileStore.length > 0) { document.getElementById("divDroppedFiles").style.display = "block"; } return false; }.bind(this); – Syed Nasir Abbas Jul 29 '20 at 18:55