我在Chart.js 2.4.0中使用了折线图,并且我已经注册了一个插件,可以随时显示工具提示,而不仅仅是在悬停一个数据点时。
enableChartToAlwaysShowTooltips(): void {
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
if (dataset.data.length === 1) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
}
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
}
你看我注册了一个新的插件,但是我想在程序上以某种情况“取消注册”这个插件,即不应该发生这个插件提供的功能。
我正在搜索任何API文档以及“删除”或“取消注册”等方法,但这没有帮助。
有什么建议吗?
答案 0 :(得分:0)
您注册的插件已覆盖了两种方法,beforeRender
和afterDraw
,如果chart.config.options.showAllTooltips
为false
,这两种方法绝对不会执行任何操作。因此,要禁用插件的功能,您可以手动操作图表对象并将chart.config.options.showAllTooltips
设置为false
。
警告1:之后您可能需要update
图表才能应用更改。
警告2:您可能需要稍微更改插件的代码,因为当前代码与chart.options.tooltips.enabled
混淆。您可以else
部分if
,这将恢复chart.options.tooltips.enabled
的值。或者您可以保留插件代码,并手动设置所需的chart.options.tooltips.enabled
值以及chart.config.options.showAllTooltips
的值。