The 'x' you use inside the listener callback comes from the surrounding
closure, therefore it is the very same loop variable. Depending on when the
listener is invoked, the value of 'x' may be the last element of the charts
object (if the callback is invoked after the loop completed) or some other
element.
Not sure why Chrome and IE work fine, I guess it may depend in differences
in the order in which callbacks are executed with respect to the caller.
Anyway, the correct way to deal with it, is to capture the 'current' x in
the loop with an additional closure, like this:
for (x in charts) {
listener[x] = g.v.events.addListener(charts[x]['chart'], 'ready' ,
(function(x) {
})(x));
...
}
Notice the anonymous callback function which is invoked passing it the
current 'x' value, ensuring the corresponding closure won't have its value
changed as the loop progresses.
See:
https://developer.mozilla.org/en/JavaScript/Guide/Closures#Creating_closures_in_loops:_A_common_mistake
http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
- R.
On 3 January 2012 23:15, asgallant <[email protected]> wrote:
> I have some code that is basically like this:
>
> var finished = {};
> var listeners = {};
> for (x in charts) {
> listener[x] = google.visualization.events.addListener(charts[x][
> 'chart'], 'ready' function () {
> finished[x] = true;
> // further processing
> google.visualization.events.removeListener(listener[x]);
> });
> charts[x]['chart'].draw(charts[x]['data'], charts[x]['options']);
> }
>
> which works fine in Chrome and IE. In Firefox, when the event listeners
> fire, they almost always have x equal to the last element in the charts
> object (occasionally, they have x equal to an earlier element, but never
> the correct one). The net result is:
> a) I can never tell when all of the charts have finished drawing
> b) the event handlers for most of the charts stick around to potentially
> cause problems on redraw
>
> Anyone have any ideas on how I can work around this?
>
> --
> 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/-/gtuC6PYjt_oJ.
> 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.
>
--
You received this message because you are subscribed to the Google Groups
"Google Visualization API" group.
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.