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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With