Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!