my problem is that I need handle multiple events for rectangle. That sound simple,
for example this works
node.click(function(e){
click(); // this is function defined in same scope, it works ok
});
node.mouseout(function(e){
mouseout();
});
But, I want to automatize this, so it should looks like this:
var events = new Array("click", "mouseout");
for(var i in events){
node[events[i]](function(e){
events[i](); /*THIS is problem, no matter if it is click or mouseout
this always fires function with same name as last item
in events array (in this case mouseout)
*/
}
}
Do you have any idea why a how I should solve it?
Your handlers created in a loop are sharing a variable. By the time they are called, the variable is the last value in the loop.
You have to use a technique I call “freezing your closures” so that each handler gets a separate copy of the shared variable. In your case, the shared variable that changes is
iYour other problem is that you want to call your functions “click/mouseout” from a string, so you have to get a handle to the function, right now your code is attempting to call
"hello"()which does not workYour last problems (but not a bug yet) are that you shouldn’t use the Array constructor and you shouldn’t use a
for inloop to iterate over arrays.The above example is easier to comprehend but you could use self invoking anonymous functions to do the same thing