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.