> From: Terry B
> 
> I have a bunch of events and I loop through them.  I would 
> like to create a double-click effect so that I call function 
> "eventDoubleClick" but I want that event to pass its index value, as
> such:
> 
> for (i=0, i<arrayLength; i++)
> {
>     $t("#event_" + i).dblclick(function () {eventDoubleClick(i)}); }
> 
> 
> Basically all the above does is then setup so that all the 
> event dblclicks are calling eventDoubleClick(i) which uses 
> the last i value; instead of setting them up as 
> eventDoubleClick(1), eventDoubleClick(2), .... eventDoubleClick(n)

As is so often the case, what you want is a closure. Get that "i" variable
to be a local variable in a function called inside the loop. Here is one way
you could code it:

   for(i=0, i<arrayLength; i++) {
      (function( i ) {
         $t( "#event_" + i ).dblclick( function () { eventDoubleClick(i);
});
      })( i );
   }

If that seems too obscure, this does the same thing in a more spelled-out
way:

   function addclick( i ) {
      $t( "#event_" + i ).dblclick( function () { eventDoubleClick(i); });
   }

   for(i=0, i<arrayLength; i++) {
      addclick( i );
   }

Either way, each time you call the function inside the loop, it creates a
new closure that has its own copy of the "i" variable.

-Mike

Reply via email to