The problem is that as your for loop keeps iterating, the value of e
inside your handler is updating too. To get around this function you can wrap the handler in a function to which you pass e
(this is called a 'closure'). It works by creating a new scope for your event variable, and thus is unchanged as the for loop increments, or you can use bind (I believe)
for (e in CanvasIO.events) {
CanvasManager.canvas.on(e, function(event){
return function(data){
CanvasIO.socket.emit("canvas:event", {
eventType: event,
data: data
});
};
}(e));
}
or
for (e in CanvasIO.events) {
CanvasManager.canvas.on(e, function(event, data){
CanvasIO.socket.emit("canvas:event", {
eventType: event,
data: data
});
}.bind(null, e));
}
This is a pretty annoying problem that comes up all the time, here's some more info: Javascript infamous Loop issue?