Search code examples
node.jssocket.ioanonymous

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?


Solution

  • 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));
        });
      }
    }