0

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 Answers 2

1

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();
            }
          }
     });

}

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

You mean like this : onClick : function((elements) => { hello(); })
No, arrow function is another way to write function in ES6, e is the event handler in your case. Check the link below. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.