[Chartjs]-How to access class variables inside chart.js custom tooltip interface

3πŸ‘

βœ…

To make this equal to the class, write it as an arrow function:

custom: () => {
 console.log(this); // should be the class
}

But sometimes you need a handle of this and that where this is the class and that is the Chart object.

Create a utility function:

export const thisAsThat = (callBack: Function) => {
    const self = this;
    return function () {
      return callBack.apply(self, [this].concat(Array.prototype.slice.call(arguments)));
    };
  }

Then:

import { thisAsThat } from './where/thisAsThat/is/located';
....
custom: thisAsThat((that: any, otherArgument: any) => {
  console.log(this); // the class
  console.log(that); // the chart object
})

TypeScript: How to use both fat arrow and this?

Leave a comment