0

在第一个图表“config.categoriesChart”的条形图单击事件上获取控制台错误“ chart.js:10403 Uncaught TypeError: Cannot read property 'handleEvent' of undefined在此处输入图像描述,显示为 chart.legend.handleEvent(args.event );

该问题发生在销毁柱上的第一个图表单击第一个图表的事件后。

但是如果我使用 $('#how_i_spend_canvas').replaceWith($('')); 它工作正常而不会破坏图表。 在此处输入图像描述

请让我这是什么问题?

document.ready 中的所有代码

let Chart = require('chart.js');/
let ChartDataLabels = require('chartjs-plugin-datalabels');
let config = window.MvpFE.globalConfiguration.howISpend; 
let dataChart = window.dataHowISpendCharts;
   let labels = dataChart.howISpendDataCatgories.map(function (e) {
    return e.label;
});

let data = dataChart.howISpendDataCatgories.map(function (e) {
    return e.data;
});

//Chart Axis's
let scales = {
    x: {
        ticks: {
            font: {
                size: config.size,
            },
            color: config.dataLabelsColor,
        },
    },
    y: {
        display: false,
    }
};
//Chart legend
let plugins = {

    legend: {
        display: false,
    },
    tooltip: {
        enabled: true,
    },

};
//Chart Data Labels
let dataLabels = {
    color: config.dataLabelsColor,
    anchor: 'end',
    align: 'top',
    offset: 0,
    formatter: function (value) {
        //Include a dollar sign 
        return '$' + value.toLocaleString();
    },
};
//chart data 
let howISpendChartdata = {
    labels: labels,
    datasets: [{
        data: data,
        backgroundColor: config.catogriesBackgroundColor,
        borderColor: config.catogriesBorderColor,
        hoverBackgroundColor: config.unSelectedColor,
        hoverBorderColor: config.unSelectedColor,
        borderWidth: config.barWidth,
        borderRadius: config.barRadius,
        borderSkipped: 'false',
        datalabels: dataLabels
    }]
}

// Category heading label text will be from json data
let categoryLabel = "";
//Array to store the bar background colors.
const barColors = [];

//Code to draw Chart 
var ctx = document.getElementById('how_i_spend_canvas').getContext('2d');
config.categoriesChart = new Chart(ctx, {
    type: 'bar',
    data: howISpendChartdata,
    // Chart pulgins & Options
    plugins: [ChartDataLabels],
    options: {
        responsive: true,
        maintainAspectRatio: false,
        aspectRatio: 2,
        plugins: plugins,
        scales: scales,
        onClick: function (evt, element) {
            if (element.length > 0) {
                const categoriesChart = config.categoriesChart;
                let activeBarIndex = element[0].index;
                categoryLabel = categoriesChart.data.labels[activeBarIndex];
                
                // destroy any chart instances that are created
                if (categoriesChart instanceof Chart) {
                    categoriesChart.destroy();
                }

                //$('#how_i_spend_canvas').replaceWith($('<canvas id="SelectedCategory" height="400px"></canvas>')); //replace current canvas
                // Code to draw Chart
                config.monthlyChart = new Chart(ctx, {
                    type: 'bar',
                    data: howISpendChartdata,
                    plugins: [ChartDataLabels],
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        aspectRatio: 2,
                        plugins: plugins,
                        scales: scales,
                        onClick: function (e, activeElements) {
                            //get the colors for bars 
                            if (activeElements.length > 0) { // check the element is selected
                                const monthlyChart = config.monthlyChart;
                                monthlyChart.options.animation.colors = false;
                                                                
                                    monthlyChart.update();
                                                                        
                                }
                            }

                        }
                    },

                });
                config.monthlyChart.render();
            }
        },
    }
}); // document.Ready Ends()
4

2 回答 2

0

我遇到了同样的问题,异常的原因是:在 onclick 事件中,如果您尝试销毁同一个图表,图表引用在事件回调函数返回之前变为空。这就是抛出异常的原因。您可以通过在事件回调完成后销毁图表实例来解决此问题,即使用 setTimeout 函数您可以在 100 毫秒左右后销毁图表。你可以这样做:

    options: {
    onClick: function (evt, element) {
        if (element.length > 0) {
            const categoriesChart = config.categoriesChart;
            let activeBarIndex = element[0].index;
            categoryLabel = categoriesChart.data.labels[activeBarIndex];

            setTimeout(() => {
                // destroy any chart instances that are created
                if (categoriesChart instanceof Chart) {
                    categoriesChart.destroy();
                }

                //$('#how_i_spend_canvas').replaceWith($('<canvas id="SelectedCategory" height="400px"></canvas>')); //replace current canvas
                // Code to draw Chart
                config.monthlyChart = new Chart(ctx, {
                    type: 'bar',
                    data: howISpendChartdata,
                    plugins: [ChartDataLabels],
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        aspectRatio: 2,
                        plugins: plugins,
                        scales: scales,
                        onClick: function (e, activeElements) {
                            //get the colors for bars 
                            if (activeElements.length > 0) { // check the element is selected
                                const monthlyChart = config.monthlyChart;
                                monthlyChart.options.animation.colors = false;
                                monthlyChart.update();
                            }
                        }
                    }
                });
                config.monthlyChart.render();
            }, 100);
        }
    }
}

以下是任何面临类似问题的人的解决方案:

options: {
    onClick: function (evt, element) {
        // get the require data from click event 
        let chart = Chart.getChart(e.chart.canvas.id);
        const points = chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, true);
        if (points.length) {
            const firstPoint = points[0];
            const elementIndex = firstPoint.index;
            const datasetIndex = firstPoint.datasetIndex;
            const dataset = chart.data.datasets[datasetIndex];
            const datasetFieldLabel = dataset.label;
            const itemLabel = chart.data.labels[elementIndex];
            const itemValue = dataset.data[elementIndex];
            
            setTimeout(() => {
                // destroy the chart
                // Render another chart
            }, 100);
        }
    }
}
于 2021-12-03T22:51:00.530 回答
0

警告:仅当您不使用图例插件或不需要处理图例项单击事件时,此解决方案才有意义。

在我的情况下,即使我legend在图表选项中禁用了插件,我也会收到此错误,如下所示:

plugins: {
  legend: {
      display: false
    }
  }

在我过滤了由图例插件处理的事件后,错误停止发生,如下所示:

plugins: {
  legend: {
      display: false,
      events: [] // this line was the key
    },
  }
于 2021-10-05T18:35:41.417 回答