Reference to source of event inside event callback?

34 views
Skip to first unread message

Jacob Fischer

unread,
Apr 10, 2012, 12:20:06 PM4/10/12
to google-visua...@googlegroups.com
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

asgallant

unread,
Apr 10, 2012, 1:27:32 PM4/10/12
to google-visua...@googlegroups.com
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 0charts.lengthi++{
    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.

Jacob Fischer

unread,
Apr 11, 2012, 3:57:49 AM4/11/12
to google-visua...@googlegroups.com
This is exactly what I was looking for.

Many thanks.
Reply all
Reply to author
Forward
0 new messages