取消注册Chart.js中的插件

时间:2016-12-20 19:29:27

标签: chart.js

我在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文档以及“删除”或“取消注册”等方法,但这没有帮助。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您注册的插件已覆盖了两种方法,beforeRenderafterDraw,如果chart.config.options.showAllTooltipsfalse,这两种方法绝对不会执行任何操作。因此,要禁用插件的功能,您可以手动操作图表对象并将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的值。