Events for presence


#1

Question from a friend:
I want to hook an event for the presence for each client, how can I do it? If there is no connection between clients at all, I’ve created a public room that every client joins on startup.


#2

The class you want to look at for that is User, it’s what other clients are represented as to you own client. You can also grab a reference to your own instance with client.user

The User instances emit events when e.g. the name or presence is changed. I see that there’s a bug in the documentation, as none of the events are listed, we’ll fix that. In any case, each user property has an event with the same name, except for id.

The Room class has a couple of different properties and events for tracking the users in a room, such as room.members and the event with the same name.

The best way to tie it all to a UI varies depending on what frameworks you may be using, although the main two ways would be to either listen for 'join' and 'leave' events and then add or remove listeners, or to listen to the 'members' event and let the UI layer figure out the what users have been added or removed.


#3

Question from friend:
Can you please list a sample for the events I need to listen on?


#4

Sure, here’s a piece of code for monitoring the presence of all members in a room, excluding oneself:

function onPresence(presence) {
  console.log(`${this} updated presence: ${presence}`)
}

// register listener for all existing members
room.otherMembers.forEach(user => user.on('presence', onPresence))

// and then keep track of members that join and leave
room.on('join', user => {
  console.log(`${user} joined room with presence ${user.presence}`)
  user.on('presence', onPresence)
})
room.on('leave', user => {
  console.log(`${user} left room with presence ${user.presence}`)
  user.off('presence', onPresence)
})

#5

Follow-up question from friend:
When a user join to a room.
It stay their (meaning the event join will not fire) again, until he kicked off or leaving, right?


#6

Correct, and you’ll be able to see the user in room.members. Although the easiest way to check the membership of a specific user is to use room.memberships, e.g. room.memberships[theUser.id] === 'member'