1

I have the following js code snippet(slightly simplified from the original) and I cannot figure out why I am getting a TypeError: this is undefined for the line this.onError(event.error.message). I understand that this is not valid in the scope but I can't wrap my head around as to why.

How can I solve this without having to pass onError to the initialize() method?

class Class1{

    constructor(props) {
        this.class2 = Class2(props.publicKey);
        this.onError = props.onError;
    }

    //initialize the form
    initialize() {

        //add error handler
        this.class2.addEventListener("change", function (event) {
            if (event.error) {
                this.onError(event.error.message);
            }
        });
    }
}
kapuetze
  • 35
  • 1
  • 8

1 Answers1

1

Assign this context to the variable and use it in callback function:

initialize() {
    var that = this;
    //add error handler
    this.class2.addEventListener("change", function (event) {
        if (event.error) {
            that.onError(event.error.message);
        }
    });
}
hsz
  • 148,279
  • 62
  • 259
  • 315
  • I actually tried this before but used it inside the callback function...Thank you, worked ver well. – kapuetze Apr 25 '18 at 09:50