0

The following code generates the error TypeError: this.SetValue is not a function.

class FlightData {
    constructor(app)
    {
        this.app = app;

        this.websocket = new WebSocket('ws://'+window.location.hostname+':20225/flight_data');
        this.websocket.addEventListener('message', this.HandleSocketMessage);
    }

    SetValue(name, value)
    {
        console.log(name + ": " + value);
    }

    HandleSocketMessage(e)
    {
        this.SetValue("name", "value");
    }
}

If I do the following instead, it works. However I am trying to avoid closures (even though the one here is harmless) in my code:

this.websocket.addEventListener('message', e => {
        this.SetValue("name", "value");
});

Can someone please explain why the code at the top doesn't work and what I need to do to make it work?

AlastairG
  • 4,119
  • 5
  • 26
  • 41

1 Answers1

3

It's a bit tricky to understand, but you need to bind the current context to the callback function. Otherwise, the context called is the callback's own.

this.websocket.addEventListener('message', this.HandleSocketMessage.bind(this) )
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 1
    So clearly explained - I have spent ages on this, especially since I am considering abandoning my javascript framework (Vue) due to memory leak issues. I am rewriting a single component in completely raw javascript to determine whether the error is in my code or Vue, and I was completely stuck. Thankyou so much! – AlastairG Feb 06 '20 at 12:39