Ad

Call A Function From Within EventListener

- 1 answer

I want to call a function from within the eventListener

I get this error : 
TypeError: this.foo is not a function

I understand that this is the xhr itself and not the class that wraps both function.

How can I call foo from within the eventListener callback?

createStripeUser = async (code) => {

    const xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function () {
        if (this.readyState === 4) {
             this.foo(this.responseText)
        }
    });

    xhr.open("POST", "https://connect.stripe.com/oauth/token");
    xhr.send(data);
}
foo  = (data ) => {
    console.log(data)
}
Ad

Answer

If you want access this from outside you need to use () => {} instead of function() {} in readyStateChange callback.

createStripeUser = async (code) => {

const xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", () => {
    if (xhr.readyState === 4) {
         this.foo(xhr.responseText)
    }
});

xhr.open("POST", "https://connect.stripe.com/oauth/token");
xhr.send(data);

foo  = (data ) => {
    console.log(data)
}

i don't know your code is a class or not. but if it not, just call foo(xhr.responseText) instead.

Ad
source: stackoverflow.com
Ad