Search code examples
jquerygoogle-visualizationdonut-chart

Google Chart API callback function not getting called


I am trying to render data using Google Chart API, but strangely when I load the visualization API, the callback function does not get called. I have created a fiddle at http://jsfiddle.net/jagzviruz/ZBMnh/

var DonutChart = {
data : [
    ['Sales', 20],
    ['Returns', 12],
    ['Pending', 80],
    ['Processed',990]
],
init : function(){
    $.getScript('https://www.google.com/jsapi', this.loadPackages);
},
loadPackages : function(){
    console.log('Loaded API.. now loading packages');
    var o = this;
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(o.renderData);
},
renderData: function(){
    //console.log('Loaded Packages.. Now showing charts');
    alert('Render Data');
}};

DonutChart.init();

I never get the alert. Other console messages appear fine.


Solution

  • Use DonutChar rather than this to reference the function pointer:

    $.getScript('https://www.google.com/jsapi', DonutChart.loadPackages);
    

    The init function is equivalent to:

    function foo()
      {
      $.getScript('https://www.google.com/jsapi', this.loadPackages);
      }
    
    DonutChart.init = foo
    

    As a result, this is equal to foo rather than DonutChart.