I had this exact same problem: i is being evaluated at the time the event 
fires, not at the value it was when it was within the loop.  The solution 
is to use a closure, and return a function from within the closure:

for (var i = 0; i < charts.length; i++) {
    google.visualization.events.addListener(charts[i], "ready", (function (x
) {  // note the "(" before "function" 
        return function () {
          charts[x].setSelection([{}]);
        }
    })(i));  // note the ")(i)" after the function closes 
} 

which binds the variable i to the (local) variable x within the closure. 
 Each handler gets its own 'x' value.

On Tuesday, April 10, 2012 12:20:06 PM UTC-4, Jacob Fischer wrote:
>
> So, I have a number of charts on the same page, and I want to handle their 
> "ready" event with a generic handler.
>
> Say I have an array of charts called charts. I want to do something like 
> this (except the following method doesn't work, but I hope it gets the 
> point across):
>
> for (var i = 0; i < charts.length; i++) {
>    google.visualization.events.addListener(charts[i], "ready", function () 
> {
>       charts[i].setSelection([{}]); // Here I want to reference the chart 
> object that fired this event. Doing it like this does not work.
>    });
> }
>
> It would be really nice if charts passed themselves along as a parameter 
> to the handler, but as far as I can read out of the documentation, this is 
> not the case.
> Basically, I want the equivalent of using $(this) inside a jQuery event 
> handler. 
>
> Is this possible?
>
> Thanks
>

-- 
You received this message because you are subscribed to the Google Groups 
"Google Visualization API" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/google-visualization-api/-/A__uU2pjMVgJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-visualization-api?hl=en.

Reply via email to