Question

This is directly taken from Professional Node.js book. I understood the logic of the code but i did not understand from where did "oldroom" appear ! The 2nd line is very confusing to me. Here we want to associate the socket with the room. The socket has not yet joined the room so in the 2nd line why are we doing socket.get('room',.....). Can we omit 2nd and 3rd lines ?

    socket.on('join', function(room) {
    socket.get('room', function(err, oldRoom) {
      if (err) { throw err; }

      socket.set('room', room, function(err) {
        if (err) { throw err; }
        socket.join(room);
        if (oldRoom) {
          socket.leave(oldRoom);
        }
        socket.get('username', function(err, username) {
          if (! username) {
            username = socket.id;
          }
        });
        socket.emit('serverMessage', 'You joined room ' + room);
        socket.get('username', function(err, username) {
          if (! username) {
            username = socket.id;
          }
          socket.broadcast.to(room).emit('serverMessage', 'User ' + 
            username + ' joined this room');
        });
      });
    });
  });
Was it helpful?

Solution

i did not understand from where did "oldroom" appear !

oldRoom "appears" or is declared as a named argument for a callback function that starts on the 2nd line:

socket.get('room', function(err, oldRoom) {
//                               ^^^^^^^

Its value will be determined when socket.get() eventually calls this function.


Can we omit 2nd and 3rd lines ?

Probably not.

The snippet appears to be limiting users to a single room when they request to 'join' one:

socket.on('join', function(room) {
    // ...
});

Lines 2-3 retrieve the user's current 'room' as oldRoom:

socket.get('room', function(err, oldRoom) {
  if (err) { throw err; }

  // ...
});

And, if they were actually in an oldRoom, they'll then .leave() it:

    if (oldRoom) {
      socket.leave(oldRoom);
    }

And .join() the requested room, updating their 'room' for the next 'join' request:

  socket.set('room', room, function(err) {
    if (err) { throw err; }
    socket.join(room);

    // ...
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top