[Chartjs]-Calling a TypeScript function from a Chart.js option callback

8πŸ‘

βœ…

I imply that your chartTestMethod is in the same class as chartOptions since you’re using it on this. You should make sure you understand how this is handled in JavaScript (and TypeScript being a superset of JavaScript). There must be a million references out there.

Without knowing anything about Chart.js, I think it is safe to assume that in no way the this context fits your class instance when onComplete is invoked. So what you want is an arrow function, like this:

onComplete: () => { this.chartTestMethod(); }

Read about TypeScript arrow function to understand how to make sure this is actually pointing to your instance.

1πŸ‘

You got an error because this if referring to the object where function is executing. In your case, this is referring to any.animation object which do not have chartTestMethod key. You can solve it depending on where chartTestMethod is defined. If it is defined in global object, you can just remove this keyword. You can rewrite your code like this

function chartTestMethod(){
    console.log('chartTestMethod called.');
}

any = {
    animation: {
        duration: 2000,
        onComplete: function (){
            chartTestMethod();
        }
    },
    responsive: true
};

Also, if you want this method to be in the same object, you can do this

any = {
    animation: {
        duration: 2000,
        onComplete: function (){
            this.chartTestMethod();
        },
        chartTestMethod: function(){
            console.log('chartTestMethod called.');
      }
    },
    responsive: true
};

0πŸ‘

you can use bind(this) 

public chartOptions: any = {
    animation: {
        duration: 2000,
        onComplete: function () {
            //alert('anim complete');
            this.chartTestMethod();
        }.bind(this)
    },
    responsive: true
};

Leave a comment