can't call any function inside of onClick function chart.js

1k Views Asked by At

I cannot call any function inside of the onClick function of chart.js. cannot even change public variable values.

initializeGraph() {
 this.graph = new Chart('graph', {
  type: 'pie',
   data: {
    datasets: [{
     data: [1,2],
      backgroundColor: ['#RRGGBB', '#FF0000'],
     }],
      labels: ['blue','red']
    },
   options: {
    onClick : function(event,elements) {
     this.hello();
    }
   }
  });
 }

 hello() {
  console.log("i am here");
 }
2

There are 2 best solutions below

0
On BEST ANSWER

Could you try

initializeGraph() {
    const that = this;
    this.graph = new Chart('graph', {
        type: 'pie',
          data: {
            datasets: [{
              data: [1,2],
              backgroundColor: ['#RRGGBB', '#FF0000'],
            }],
            labels: ['blue','red']
          },
          options: {
           onClick : function(event,elements) {
              that.hello();
            }
          }
     });

}

2
On

Did you try using arrow function? (e) => {} The this variable’s scope is different when using arrow function. The arrow function inherit the ‘this’ from the parent scope, which in your case might refers to global scope.