I’m debugging a bit of Javascript that was suffering from a little closure trouble – but don’t seem to be able to pass the “event” argument into the function.
Here’s the problem (in shorthand):
// let's say links.length == 3
for(var i = 0; i < links.length; i++){
links[i].onclick = function(e){
alert(i); //closure! all links alert "3"
// do something with "e"
}
}
Here’s my solution
//workaround
// define function outside of loop
function outer(e,i){
return function(){
alert(i); //closure! all links alert "3"
// do something with "e"
}
}
for(var i = 0; i < links.length; i++){
links[i].onclick = outer(e,i); //uh oh! e = undefined???
}
In my workaround, I’ve defined a function outside the loop to prevent closure – but I am unable to pass the “e” argument to it. Can someone point me in the right direction?
Define it in the returned function.
The
eventobject gets passed when the event occurs, so it needs to be defined as a parameter to the function that is ultimately assigned as the handler (the function you’re returning fromouter()).