I had a working JS code to display some google chart on page. I thought I refactor this into a JS class like this (cleared and minimized the code for the sample):
class MyChar {
show(title) {
this.title = title;
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(this._googleChartOnLoadCallback);
}
_googleChartOnLoadCallback() {
console.log("_googleChartOnLoadCallback is called", this.title);
// do stuff needed here
}
}
I want to call this like this:
var myChart = new MyChart();
myChart.show("My cool chart");
I expected to see on the developer console the title, but got an error pointing to the 1st line of the _googleChartOnLoadCallback method:
Uncaught (in promise) TypeError: this is undefined
The google chart loader is (of the html head):
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
My question is: can or cannot use a class method on a callback - or am I missing something? If I cannot use a callback - then how to insert (add) chart specific data to the callback func?
Thanks in advance!
Found a solution:
var f = this._googleChartOnLoadCallback.bind(this);
google.charts.setOnLoadCallback(f);