prismflux
prismflux

Reputation: 67

socket.io anonymous callback: can't call class functions

So, I have the following piece of code:

class Server {
  dataHandler(d) {
    console.log(d);
  }
  init() {
    io.on('connection', function(socket) {
      socket.on('data', this.dataHandler(d); //<-- TypeError: this.dataHandler is not a function
    });
  }
}

I want to process the data of the data socket, but how can I escape the anonymous function environment and access this.dataHandler()? Even when I call dataHandler() or instance.dataHandler() (an object which stores the Server) it can't find that function.

Can someone explain that to me?

Upvotes: 0

Views: 290

Answers (1)

Mikhail Burshteyn
Mikhail Burshteyn

Reputation: 5012

This happens because of incorrect use of this.

You should use an arrow function which will preserve the this context:

class Server {
  dataHandler(d) {
    console.log(d);
  }
  init() {
    io.on('connection', (socket) => {
      socket.on('data', this.dataHandler(d));
    });
  }
}

Upvotes: 1

Related Questions