如何在高图表点击事件中调用打字稿功能

Pra*_*A.K 3 charts this highcharts typescript angular

MyHighChartComponent.ts

export class MyHighChartComponent {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click(e) {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this is printing
                        this.drillDown(); // how to call typescript function here?
                    }
                },
            },
        }
    };  

    drillDown() {
      console.log('drill down method called');
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从高图表点击事件内部调用打字稿函数?

我得到以下错误

错误堆栈:TypeError:this.drillDown 不是函数

tos*_*skv 5

您必须使用箭头函数在单击处理程序中保留相同的上下文 (this)。

它看起来像这样:

export class MyHighChartComponent {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click : (e) => {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this is printing
                        this.drillDown(); // how to call typescript function here?
                    }
                },
            },
        }
    };  

    drillDown() {
      console.log('drill down method called');
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要访问图表上下文和类上下文,您可以手动将类上下文保存在一个变量中(就像在箭头函数出现之前所做的那样)。

class MyHighChartComponent {
  public highchartsConfig() {
    var that = this; // store this in a variable to use later
    return {
      chart: {
        events: {
          click: function(e) {
            if (!($(event.target)[0].textContent)) {
              console.log('clicked');
              // this variable now stores the chart
              // call methods on class using the that variable
              that.drillDown();
            }
          },
        },
      }
    };

  }
  public drillDown() {}
}
Run Code Online (Sandbox Code Playgroud)