Question

Here is my javascript code.

//Events to watch
CanvasIO.events = [
    "object:added",
    "object:removed",
    "object:modified",
    "object:rotating",
    "object:scaling",
    "object:moving"
];

//Socket connection
CanvasIO.socket = io.connect('http://localhost:8080');

//Canvas events fired
for (e in CanvasIO.events) {
    CanvasManager.canvas.on(e, function(data){
        CanvasIO.socket.emit("canvas:event", {
            eventType: e,
            data: data
        });
    });
}

//Socket IO event received
CanvasIO.socket.on("canvas:event", function(data) {
    console.log("Received: " + data.eventType);
});

My problem is that in the Canvas Event Fired part I wish to generate automatic messages to be emitted based on the events name. But because I use eventType: e every message will get the last state of e, "object:moving".

So, for:

CanvasManager.canvas.on(key, handler)

Would it be possible to access the key within the handler? If not, how should I proceed?

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top