Typescript中的JavaScript回调。同时访问类成员和javascript'this'参数

时间:2018-11-26 18:06:00

标签: typescript highcharts angular2-highcharts

我正在为名为HighCharts的库使用Angular包装器。当我将鼠标悬停在图表上时会有一个回调,这是一个JavaScript回调。此javascript函数的this参数为我提供了所需的数据,但我也想使用Typescript this键盘访问我的Typescript类变量。

const options: Highcharts.Options = {
  chart: {
    type: 'column'
  },
  title: {
    text: null
  },
  tooltip: {
      borderWidth: 0,
      style: {
          padding: 0
      },
      useHTML: true,
      formatter: function() {
          return '<div style="float:left">' +
        '<small>Hour ' + this.point.x + '</small>' +
        '</div>' +
        '<div style="float:left;">Production: <b>' + this.point.y + '%</b></div>' +
        '<div style="float:left;">Yield: <b>' + this.yieldCurrent + '%</b></div>' +
        '<div style="float:left;">Reject: <b>' + this.rejectCurrent + ' pcs.</b></div>' +
        '<div style="float:left;">Uptime: <b>' + this.uptimeCurrent + '%</b></div>';
      }
   }
}

如果我使用funtion() {},则可以访问highcharts提供的this

如果我使用粗箭头() =>,则可以访问班级提供的this

如何在回调中访问这两个参数?我需要从课程表中访问this.point,并从我的课程中访问this.yieldCurrentthis.rejectCurrentthis.uptimeCurrent

2 个答案:

答案 0 :(得分:1)

您可以将组件引用保存在图表对象中,然后在tooltip.formatter函数中使用它。

在组件构造函数中保存组件引用:

  constructor() {
    const self = this;

    self.chartCallback = chart => {
      self.chart = chart;
      chart.chartComponent = self;
    };
  }

tooltip.formatter中使用它:

tooltip: {
  formatter: function() {
    const chart = this.series.chart,
      chartComponent = chart.chartComponent;

    return this.y + " - " + chartComponent.yourProperty;
  }
}

演示:https://codesandbox.io/s/vmvylr0v2y

答案 1 :(得分:0)

您可以将类的this对象引用到某个变量,然后在formatter函数中使用它。

像这样在顶部或构造函数中的某个位置初始化const

const self = this;

然后在该对象已更改的代码内的任何位置使用它。

const options: Highcharts.Options = {
  chart: {
    type: 'column'
  },
  title: {
    text: null
  },
  tooltip: {
      borderWidth: 0,
      style: {
          padding: 0
      },
      useHTML: true,
      formatter: function() {
          return '<div style="float:left">' +
        '<small>Hour ' + this.point.x + '</small>' +
        '</div>' +
        '<div style="float:left;">Production: <b>' + this.point.y + '%</b></div>' +
        '<div style="float:left;">Yield: <b>' + self.yieldCurrent + '%</b></div>' +
        '<div style="float:left;">Reject: <b>' + self.rejectCurrent + ' pcs.</b></div>' +
        '<div style="float:left;">Uptime: <b>' + self.uptimeCurrent + '%</b></div>';
      }
   }
}

希望这会有所帮助