'this' inside event listener callback overrides 'this' class

24 Views Asked by At

What is the best way to structure the following code?

I have a part of code on client side that is responsible for communicating with a PHP server. It is sending some data to it, the server then based on type of request modifies the database or just retrieves some data from it which it then sends back to the client as a response.

My first idea was to encapsulate client code in a class named Foo. It would open the connection inside of its constructor. When upper layer wanted to request data modification or retrieval it would call one of many Foo methods which would prepare and send a request to PHP server via this.#httpRequest.send(). Once Foo received a response it would extract the relevant data and call the upper layer provided callback function this.onReceiveOk.

An example code and problem:

class Foo {
    #httpRequest;
    onReceiveOk;

    constructor() {
        this.#httpRequest = new XMLHttpRequest();
        this.#httpRequest.addEventListener('load', this.#handleLoad);
    }

    #handleLoad() {
        this.onReceiveOk(this.#httpRequest.responseText); // ERROR: 'onReceiveOk' is not a function
    }
}

However I noticed that when method #handleLoad is called the context for this is no longer Foo class. I did some googling and found that in this case the context is the calling function, so the XMLHttpRequest class.

Is there a way to make the context of #handleLoad be Foo class? Is this code structuring the standard way or should I change something about it? Should I use closures instead of classes for this particular case? I have used class so that code is modular and I can import the class in upper layer.

0

There are 0 best solutions below