Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda