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