user3787706
user3787706

Reputation: 659

attaching properties to sockets across events

i found out that i can attach names etc to socket.io sockets.

this works fine.

however i want to retrieve that same data on another event.

this should show it pretty clearly:

socket.on('studentJoinRoom', function answerStudentJoin(msg) {

    var userName = msg.userName;
    var roomId = msg.roomId;

    console.log('user ' + userName + ' joining room ' + roomId);
    socket.userName = userName;

    if (socket.room !== roomId) {  // only join once
      socket.room = roomId;
      testRooms.joinClient(userName, roomId);
      socket.join(roomId); // join socket room
      socket.emit('studentJoinConfirmed');
      socket.broadcast.to(testRooms.getTeacherId(roomId)).emit('newStudentJoined', {student: userName});
    }
    console.dir(testRooms.getRooms());
});


socket.on('disconnect', function(socket) {
    console.log(socket.userName + ' has left the room ' + socket.room);
})

i want to access the data from on('studentJoinRoom' inside the on('disconnect. how can i do that?

console output:

user test joining room ijzvqmau
{ ijzvqmau: 
   { Id: 'ijzvqmau',
     teacherName: 'testteacher',
     teacherId: '/#KMGUyCINopRDvf5JAAAE',
     clients: [ 'test' ] } }
undefined has left the room undefined

Upvotes: 1

Views: 91

Answers (1)

David Perez
David Perez

Reputation: 336

You must not pass to the callback function 'socket', so just remove it:

socket.on('disconnect', function() {
   console.log(socket.userName + ' has left the room ' + socket.room);
 })

Upvotes: 1

Related Questions