2

I'm building an app with some realtime features (notifications, real-time comments, ..., and of course the classic chatroom). It's structured as a single page app. I'm using page.js to handle routes, require.js, and, for now, a simple custom mvc framework. Backend with node and socket.io for the realtime support.

The thing is, I have different sections, like home, posts, chat. Each section is dynamically rendered based on the routes. Now, how should I bind specific socket events for each section? I don't want to listen to events that are unrelated to the current viewing section. Should I create a new connection everytime the user changes the section, targeting a different namespace? Or should I remove all the event listeners in the socket, and attach a new set of events? I don't know what's the best approach, or if socket.io is the best choice for this.

Thanks.

ezakto
  • 3,174
  • 22
  • 27
  • Have you looked into namespace http://socket.io/#how-to-use ? – vinayr Sep 02 '13 at 04:24
  • Yep, that's why I ask if it's a good idea to create a new connection everytime the user changes the section, targeting a different namespace... Or I'm thinking it wrong :/ – ezakto Sep 02 '13 at 04:26
  • Why do you create new connection? It's single page right (which means you are using ajax to load sections) ? – vinayr Sep 02 '13 at 04:31
  • If I'm in, let's say, home section, I have an `io.connect('/home')`. If I switch to posts section, shouldn't I create a new connection to `'/posts'`? – ezakto Sep 03 '13 at 03:30

1 Answers1

0

Wow. I found this question in google and I realized I never posted my solution.

Thanks to this answer, I solved to use rooms instead of namespaces. So when the user changes the sections, socket emits a "changeSection" event. In serverside, I leave the room corresponding the old section and join the new one:

io.sockets.on('connection', function (socket){
  socket.on('changeSection', function (section){
    // Leave all previous rooms
    for (var room in io.sockets.manager.roomClients[socket.id]) socket.leave(room.slice(1));
    // Join new
    socket.join(section);
  });
});

Then I send section-specific events (like notifications, new comments, chat messages) to the corresponding room.

Community
  • 1
  • 1
ezakto
  • 3,174
  • 22
  • 27