Possible Duplicate:
How do JavaScript closures work?
I've read all the million duplicates of the same old javascript closure loop issue. I thought I understood them, and have been using closures for months without issue, until today. I am stumped.
for (var i in groups){
for(var j in groups[i]){
$(unique_form).die('submit').live('submit'), function{
function (groups2, i2, j2){
return function(){alert(groups2[i2][j2])}
}(groups, i, j)
}
});
}
}
}
When I submit each unique form - I keep getting an alert for the last element of groups[i][j]. Obviously, I'm doing something stupid, what is it? I thought that by creating the anonymous function groups2, i2, and j2 I was solving the problem.
The function you pass to .live()
is executed when the submit event is fired. By that point, i
and j
will have their final values. You would need to create the closure outside of the event handler:
(function (i2, j2) {
$(unique_form).die('submit').live('submit', function{
alert(groups[i2][j2])
});
}(i, j));
Notice that I've removed the groups
argument from the anonymous function. There's no need to close over that since its value won't change. I've also wrapped the entire function expression in parentheses, which is the convention (and in this case actually required, to force it to be parsed as an expression).
Also note that I've removed the closing parentheses that you have after the first argument to .live()
in your question. It shouldn't be there.
Side note.
.live()
and .die()
have been deprecated for ages now. Use .on()
(with jQuery 1.7+) or .delegate()
(with older versions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With