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');
}
}
如何从高级图表点击事件中调用打字稿功能?
我收到以下错误
错误堆栈:TypeError:this.drillDown不是函数
答案 0 :(得分:3)
您必须使用箭头功能在点击处理程序中保留相同的上下文(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');
}
}
如果您需要访问图表上下文和类上下文,您可以手动将类上下文保存在变量中(在箭头函数之前执行此操作的方式)。
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() {}
}