SISYN
SISYN

Reputation: 2259

Best practice for handling Socket.io events?

I am switching from ajax polling to socket.io live data pushing but have a question about best practice of managing events.

Let's say I have a basic server like this:

var Clients = [];
// Event fired every time a new client connects:
io.on('connection', function(socket) {
    Clients.push(socket);
    // What else should go in here?
    // Individual functions for each event?

   socket.on('chat message', function(msg){
        console.log(':> '+msg);
        io.emit('chat message', msg);
    });

    // When socket disconnects, remove it from the list:
    socket.on('disconnect', function() {
        var index = Clients.indexOf(socket);
        if (index != -1) { Clients.splice(index, 1); }
    });
});

In the example there is a chat message event, but ideally there are many other events I'd like to push to clients in real-time, such as:

User sends message, user starts/stops typing, user likes a post, user invites you to become friends/group member, and so on.

There are many events that I'd like to capture in real-time but it seems like there has to be a better way than cramming the io.on() statement full of them all.

I've looked into Node OOP but not sure if it would necessarily help in this application.

So where we have the socket.on() statements, what would the best practice be for including event catching like I described?

Upvotes: 1

Views: 2018

Answers (1)

jfriend00
jfriend00

Reputation: 707238

There are many events that I'd like to capture in real-time but it seems like there has to be a better way than cramming the io.on() statement full of them all.

Nope. Inside the io.on('connection', ...) is where you have a closure with the socket variable that pertains to a new connection. So, any event handler you want to respond to from that socket goes in there or in some function you call from there and pass the socket to. That's just how it works.

FYI, in the interest of modularity, you don't have to put all the event handlers inside of one io.on('connection', ...). If you export the io object to other modules or pass it to them in a module constructor, you can have other modules create their own io.on('connection', ...) listeners and install their own event handlers inside their own io.on('connection', ...). io is an EventEmitter so it can support as many listeners for the connection event as you want and all will be notified.

Upvotes: 5

Related Questions