Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass variables to an event javascript - no closures, no jq, avoid evals & such

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!
    }
}
  • All over the place the solution for this is said to be closures - wow great! except closures break ie (right?)
  • Elsewise, I can eval the code on the spot, baking in the varibles, but that seems ugly at best, and seems like it might break some thing

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

like image 621
Trass Vasston Avatar asked Dec 08 '25 12:12

Trass Vasston


1 Answers

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.

like image 59
alex Avatar answered Dec 10 '25 01:12

alex