Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Socket.io callback function scope

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda