Skip to content Skip to sidebar Skip to footer

Socket.io Using A For Loop To Add Socket.on Methods

Assume socketMethods:{ update:function(data){ this.emit('test', data); console.log('socket.update'); }, test:function(data){ this.emit('test', d

Solution 1:

You're making the common mistake of assuming that a closure "traps" the value of an outer function's variable at the time it was created. It doesn't. It "traps" a reference to the outer function's variable, and its value will be whatever the outer variable has at the time the closure is executed. If you're creating closures in a loop, that value will be whatever it had at the end of the loop.

The way to get around this is to create an "enclosing" closure that uses the outer variable's value as argument. One way to do this is to create a helper function that generates your closure. In your first example, you could do

function makeOn(key) {
  return function(data) {
    dummy.socketMethods[key].call(socket, data);
  }
}

for(key in dummy.socketMethods){
  socket.on(key, makeOn(key));
}

Now in each closure, key will be a newly-created variable (differing between closures) set to the appropriate value.

It's also possible to use an immediate function call (what some call a "self-executing function") to do the same thing a little more succinctly, but also somewhat less readably.

Post a Comment for "Socket.io Using A For Loop To Add Socket.on Methods"