在嵌套事件处理程序中传递参数



我使用Highcharts来显示自定义国家的交互式地图,我需要激活钻取功能,即单击一个国家以放大另一个具有该国内部状态的地图。

在angular中,我们可以在chartOptions对象中添加一个钻取事件处理程序,在其中加载地图数据,然后调用一个函数将地图数据作为钻取添加到图表中。

export class MapComponent implements OnInit {
public chartOptions: Highcharts.Options = {
chart: {
events: {
drilldown(e) {
// At this point "this" is a Highcharts.MapChart object.
const chart = this as any;
const mapKey = `countries/ca/${e.point.drilldown}-all`;
const mapData = require(`@highcharts/map-collection/${mapKey}.geo.json`);
const provinceData = Highcharts.geojson(mapData);
// Filling map data with meaningless values becaus it's just an example.
provinceData.forEach((el: any, i) => { el.value = i; });
// Here's the key, the Highcharts.MapChart object is required to add the new map data.
chart.addSeriesAsDrilldown(e.point, { name: e.point.name, data: provinceData });
}
}
}
}
}

然而,由于我没有使用Highcharts提供的地图数据之一,而是使用SVG文件生成的自定义地图数据,并位于mongo数据库中,该数据库在启动时从数据库加载并存储在mapcomponent的属性中,我需要使用"this"访问该属性在事件处理程序函数的组件范围内。

export class MapComponent implements OnInit {
private drilldownData: Highcharts.SeriesMapOptions = { ... };
public chartOptions: Highcharts.Options = {
chart: {
events: {
// Here "this" is of course in the scope of the MapComponent.
drilldown: this.handleDrilldown
}
}
}
private handleDrilldown(e: Highcharts.DrilldownEventObject): void {
// At this point "this" is a Highcharts.MapChart object.
let chart = this as any;
// Now, of course, the drilldownData is undefined because "this" required here is not the MapComponent.
chart.addSeriesAsDrilldown(e.point, { name: e.point.name, data: this.drilldownData });
}
}

我试过将钻取称为drilldown: event => this.handleDrilldown(event),但随后"this"handleDrilldown里面是MapComponent,我没有办法得到Highcharts。MapChart对象。这同样适用于drilldown: this.handleDrilldown.bind(this),它将内部作用域覆盖到MapComponent的。drilldown: function(event) { this.handleDrilldown(event) }当然也不起作用,因为现在"this"函数内部已经是Highcharts了。MapChart对象,因此没有handleDrilldown方法。是否有一种方法可以让我以某种方式将drilldownData传递到这个星座的事件处理程序中,同时保持Highcharts的范围。MapChart内部的事件处理程序?

你可以使用IIFE结构来使用'double' this:

chart: {
events: {
drilldown: (function(MapComponent) {
return function(e) {
console.log(MapComponent, this);
}
})(this)
}
}

现场演示:https://jsfiddle.net/BlackLabel/zputgf1q/

文档:https://developer.mozilla.org/en-US/docs/Glossary/IIFE

最新更新