在单击事件的工具提示下的自定义工具提示中的以下代码片段中,当我尝试使用它时,类变量无法访问,它仅显示与 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
}
但有时您需要 this
和 that
的句柄,其中 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
})
关于javascript - 如何访问 Chart.js 自定义工具提示界面中的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843427/