如何在高图表点击事件中调用Typescript函数 [英] How to call typescript function inside High chart click event
本文介绍了如何在高图表点击事件中调用Typescript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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不是函数
解决方案
您必须使用箭头函数在点击处理程序中保留相同的上下文.
它看起来像这样:
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() {}
}
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');
}
}
How to call a typescript function from inside high charts click event?
I'm getting below error
Error Stack : TypeError: this.drillDownis not a function
解决方案
You must use an arrow function to preserve the same context (this) in the click handler.
It would look like 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');
}
}
If you need access to both the chart context and the class context you can manually save the class context in a variable (the way you'd do it before arrow functions were a thing).
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() {}
}
这篇关于如何在高图表点击事件中调用Typescript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文