acrmuui
acrmuui

Reputation: 2070

socket.io code structure: where to place methods?

When using the socket.io library, I am a little confused about how to place the different methods.

In a very simple chat application I have server.js:

io.sockets.on('connection', function(socket) {

    //some methods to handle when clients join.   

    socket.on('text', function(msg) {
        socket.broadcast.emit('text', msg);
    });
});

and client.js:

var socket = io.connect();

socket.on('connect', function() {

    //some methods to fire when client joins.   

    socket.on('text', function(msg) {
        console.log(msg)
    });
});

Right now, the methods that handle when a client joins AND the methods that handle the sending and receiving of messages afterwards, are placed within the connect / connection event methods, both on the server and the client side, but this structure seems to work as well on the client side:

var socket = io.connect();    

socket.on('connect', function() {

    //some methods to fire when client joins.   

});

socket.on('text', function(msg) {
    console.log(msg)
});

+potentially many more methods...

My question is, what is the fundamental difference between placing a method inside the connect method and outside, and what is considered the best option?

Upvotes: 2

Views: 1646

Answers (1)

user568109
user568109

Reputation: 48003

When you call this,

socket.on('xyz', function listener() {});

you listen for event xyz and add function listener as event handler. It is executed whenever xyz occurs. So when you do :

socket.on('connect', function() {
    socket.on('text', function(msg) {
        console.log(msg)
    });
});

Event handler/listener for text is added only when connect event happens (connect event handler is executed). There is only one listener before connect happens and two (one more) when connect happens. But when you do :

socket.on('connect', function() {
    //some methods to fire when client joins.   
});
socket.on('text', function(msg) {
    console.log(msg)
});

There are two listeners at any time, before/after connect happens.

The previous method is more efficient and logical. Logical because text cannot happen before connect happens, so why listen to it. Efficient as in the event-loop does not have unnecessary events to look for. Adding too many events may not hurt very much, but for performance-critical applications it can be a drag. The latter one just looks good, all event handlers placed one by one.

Upvotes: 3

Related Questions