javascript - 如何访问 Chart.js 自定义工具提示界面中的类变量

标签 javascript angular chart.js ng2-charts

在单击事件的工具提示下的自定义工具提示中的以下代码片段中,当我尝试使用它时,类变量无法访问,它仅显示与 ChartElement 相关的值

@Output() valuechange = new EventEmitter<any>();
options: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
  displayColors: false,
  mode: 'nearest',
  intersect: false,
  enabled: false,
  custom(tooltipModel: any) {
    // tooltip element
    let tooltipEl: any = document.querySelector('#chartjs-tooltip');

    // create element on first render
    if (!tooltipEl) {
      tooltipEl = document.createElement('div');
      tooltipEl.id = 'chartjs-tooltip';
      tooltipEl.style.width = '124px';
      tooltipEl.style.color = 'white';
      tooltipEl.style.borderRadius = '6px';
      tooltipEl.style.backgroundColor = 'rgba(55, 71, 79, 0.8)';
      tooltipEl.innerHTML = '<div style ="display:flex;flex-direction:column">sample tooltip</div>';
      document.body.appendChild(tooltipEl);
    }

      tooltipEl.onclick = () => {
        // NOT ABLE TO Access this to emit event 
        // this.valuechange.emit('test');
        console.log('hi); // working
      };
    }
}

最佳答案

要使 this 等于该类,请将其编写为箭头函数:

custom: () => {
 console.log(this); // should be the class
}

但有时您需要 thisthat 的句柄,其中 this 是类,that 是图表对象。

创建实用函数:

export const thisAsThat = (callBack: Function) => {
    const self = this;
    return function () {
      return callBack.apply(self, [this].concat(Array.prototype.slice.call(arguments)));
    };
  }

然后:

import { thisAsThat } from './where/thisAsThat/is/located';
....
custom: thisAsThat((that: any, otherArgument: any) => {
  console.log(this); // the class
  console.log(that); // the chart object
})

TypeScript: How to use both fat arrow and this?

关于javascript - 如何访问 Chart.js 自定义工具提示界面中的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843427/

相关文章:

具有多个模块的 Angular 2 项目结构

javascript - Chart.js - y 轴自定义标签

JavaScript 图表 : How to hide the data

javascript - 在检查谷歌表单的输入元素时,我找不到 "name"属性。如何找到它?

css - 通过 CSS 改变垫子分页器背景颜色

css - Angular material 迷你按钮周围显示一些正方形

javascript - chart.js 响应条形图标签大小

Javascript 从 PHP 获取内容

javascript - 如何创建无限滚动图库

javascript - 使用命名立即调用函数表达式 (IIFE) 而不是注释