Salvador Dali
Salvador Dali

Reputation: 222561

Socket io and closures in a loop

I wan to simplify the following code:

socket.on('event1', function(data){
    func1(data);
});
....
socket.on('eventN', function(data){
    funcN(data);
});

So I tried to create and object

var socketsMap = {
    event1      : func1,
    ...,
    eventN      : funcN
}

And I thought that I have done closures correctly with

for (var event in socketsMap){
    socket.on(event, function(data){
        return function(data){
            socketsMap[event](data);
        };
    });
}

but apparently I am missing something as only the last one is always executed.

Upvotes: 0

Views: 57

Answers (1)

Mritunjay
Mritunjay

Reputation: 25882

This should work for you:-

var socketsMap = {};

socketsMap['event1'] = function (data) {
  //code
}
.....

socketsMap['eventN'] = function (data) {
  //code 
}

for (var event in socketsMap){
    socket.on(event, socketsMap[event]);
}

Upvotes: 1

Related Questions