0

In socket.io, the basic server-side connection code typically looks somewhat like this:

// When a client connects to this server
io.on('connection', (socket) => {

    // When a player is ready to start the game
    socket.on('playerReady', (playerData) => {        
        console.log(`playerReady received from client ${socket.id} with data ${playerData}`);
    });
});

My question is about the scope of the socket variable.

For better code structure, is it possible to do something like the following, and have access to both socket and playerData within the callback function?

// When a client connects to this server
io.on('connection', (socket) => {
    
    // When a player is ready to start the game
    socket.on('playerReady', onPlayerReady);
});

// Callback function
onPlayerReady = (playerData) => {

    // Problem: socket is not defined
    console.log(`playerReady received from client ${socket.id} with data ${playerData}`);
};

NB: Caching socket as a global variable does not appear to be suitable, since it appears that it has a different value for different clients.

Ben
  • 15,938
  • 19
  • 92
  • 138
  • 1
    `const onPlayerReady = socket => playerData => { ... }` and `socket.on('playerReady', onPlayerReady(socket));` –  Jun 01 '22 at 21:08
  • 1
    Without currying you can do `socket.on('playerReady', pd => onPlayerReady(socket, pd));` and `function onPlayerReady(socket, playerData) { ... }` –  Jun 01 '22 at 21:10
  • 1
    (note that obviously none of this is in any way specific to socket.io) –  Jun 01 '22 at 21:11
  • @ChrisG Thank you, both of these options work! I think I'll go with the first one, as it reduces the number of times I have to repeat the `pd` argument. If you would like to formulate your comments into an Answer, I'd accept it. – Ben Jun 01 '22 at 21:17
  • This question is basically a dupe of this one: https://stackoverflow.com/questions/40802071/pass-an-extra-argument-to-a-callback-function –  Jun 01 '22 at 21:19

0 Answers0