0

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.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753

1 Answers1

1

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]);
}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68