ok, this has been addressed by everybody, but yet I feel no closer to understanding what to do.
I want to have a loop that sets a bunch of click handlers and have each handler given unique parameters. I'm doing somehting like this now:
for (thisThing in things){
myDiv=document.createElement('img');
myDiv.onclick=function(){
// do somehting!
// but don't do anything with "thisThing"
// because it's got the wrong value in it by the time you call it!
// but this function has to have the value of "thisThing" to work, dammit!
}
}
So what does this leave me? Are closures ok? is evaling ok? AM I THE ONLY PERSON DYNAMICALLY CREATING BUTTONS ON THE WEB?!? Any help will be much appreciated. sorry about the elementary &, in fact, frequently answered question.
this page has the most complete answer I've found thus far, however, it suggests that closures are the solution for all time. Curses! http://www.howtocreate.co.uk/referencedvariables.html
Closures do not break IE.
(function(someThing) {
myDiv.onclick=function(){
// Access it as "someThing"
}
})(thisThing);
jsFiddle.
The problem is the function assigned to the onclick property creates a closure where it has access to its parents variables.
By the time you are ready to click an element, its thisThing has been incremented to the final value that terminates the loop (the last property iterated over in your case) because it accesses the outer variable, not a copy.
By creating a new closure with a new self invoking function and passing thisThing, its value becomes the variable someThing and lives inside of the inner function only.
This is one of the ways of mitigating this known problem.
Note that in IE6 & 7 there is a memory leak. Consult RobG or Raynos's answer for a solution to this issue.
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