Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js and Socket.io - Dynamic socket.on()

I made some stuff to shrink my socket.on() code.

In this context I have already get the client socket with

...
var io = require('socket.io').listen(...);
io.sockets.on('connection', function(socket) {
    // my code for this client
    ...
});

Before I had this

socket.on('event1', function(args1) {callback1(args1);});
socket.on('event2', function(args2) {callback2(args2);});
...
socket.on('eventN', function(argsN) {callbackN(argsN);});

Now I have


    var events = {
        event1: 'callback1',
        event2: 'callback2',
        ...
        eventN: 'callbackN'
    };
    for(var event in events) {
        var callback = events[event];
        socket.on(event, function() {
            this[callback].apply(this, arguments);
        });
    }

It appears that the callbackN function is always call. When event1 is trigger with args1, callbackN is call with args1, when event2 is trigger with args2, callbackN is call with args2.

What is wrong ?

like image 805
Typhon Avatar asked Nov 02 '22 13:11

Typhon


1 Answers

This should work :

var events = {
    event1: 'callback1',
    event2: 'callback2',
    ...
    eventN: 'callbackN'
};

var setCB = function(ev) {
    var callback = events[ev];
    socket.on(event, function() {
        this[callback].apply(this, arguments);
    });
};

for (var event in events) {
  setCB(event);
}

The weird or non intuitive behavior you're seeing is well explained by this blog post.

Hope it helps.

like image 127
warchimede Avatar answered Nov 15 '22 05:11

warchimede