Search code examples
javascriptpolymergoogle-visualizationpolymer-1.0polymer-starter-kit

Access div within Polymer callback function


I have a basic Polymer app setup (one of the sample applications with 3 views in a drawer). I am trying to dynamically display Google Charts within each view. I load google charts in the Polymer ready() function and pass in a function on the setOnLoadCallback. In the callback function I try and create the chart and add it to a div, but am unable to find the div. Can anyone tell me what I am doing wrong?

<div id="chart_div" style="width: 900px; height: 500px"></div>

  <script>
    Polymer({
      is: 'my-view1',
      ready: function() {
        console.log('Polymer ready');

        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(this.drawBasic);
      },

      drawBasic : function() {
        console.log('preparing to create chart');

        var chart_div = this.$.chart_div;
        console.log(chart_div);
      }
    });
  </script>

Solution

  • I think that your mistake is here:

    google.charts.setOnLoadCallback(this.drawBasic)
    

    One way to fix this is using bind method. Here you can find documentation about that method. So, I suppose this will work:

    google.charts.setOnLoadCallback(this.drawBasic.bind(this))