0

I was using ChartJS v2.9.3 in my website and i have a function which is called in a long pool which gets data from an API where i generate the legend as with new data from API it can change.

My old code was:

$('#legend-rc').html(chartRC.generateLegend());

Now i migrated my ChartJS to the last version 3.7.0 but i get chartRC.generateLegend is not a function

By looking in the documentation it seems that generateLegend() has been removed, but how can i still do something like i was doing with v2 after migration?

NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100
  • 1
    Take a look at [this answer](https://stackoverflow.com/a/69100127/16688813). – Tom Jan 19 '22 at 08:12
  • @Tom my data is load after the chart initialization and it's updated every x seconds so i will just get empty labels if i set it in `beforeInit` – NiceToMytyuk Jan 19 '22 at 08:52

1 Answers1

0

As i my dataset is load dynamically i had to add my legend logics in afterDatasetUpdate

So my code looks like this:

const chartRC = new Chart(document.getElementById("chartRC").getContext('2d'), {
    type: 'pie',
    data: {
        labels: [],
        datasets: [{
            fill: false,
            borderWidth: 2,
            pointBackgroundColor: '#0095ff',
            pointBorderColor: 'rgba(255,255,255,0)',
            pointHoverBackgroundColor: '#4683d3',
            data: [],
        }]
    },
    options: optionsRC,
    plugins: [{
        afterDatasetUpdate: function (chart, args, options) {
            if (chart.data.labels.length) {
                const chartId = chart.canvas.id
                const legendId = `${chartId}-legend`;
                const ul = document.createElement('ul');
                ul.setAttribute('data-chart-id', chart.id)
                chart.data.labels.forEach((label, i) => {
                    ul.innerHTML += `
                    <li>
                      <span style="background-color: ${chart.data.datasets[0].backgroundColor[i]}"></span>
                      ${label}
                    </li>
                `;
                })
                $(`#${legendId}`).delegate('li', 'click', legendClick);
                $(`#${legendId}`).delegate('li', 'mouseenter mouseleave', legendHover)
                return document.getElementById(legendId).appendChild(ul);
            }
            return;
        }
    }]
});
NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100