Inline plugin doesn't work
Asked Answered
M

1

7

According to the Chart.js docs, the following code should work:

new Chart(document.getElementById(chartID), {
   type: 'pie',
   responsive: true,
   maintainAspectRatio: false,
   data: {
      labels: graph.globals.labels,
      datasets: [{
         backgroundColor: pieOptions.backgrounds,
         data: pieOptions.objToArr(graph.meetingsData),
         hoverBorderWidth: 5,
         borderColor: 'transparent',
      }]
   },
   options: {
      title: {
         display: true,
         text: graph.globals.title,
      },
      legend: {
         display: true,
         position: 'bottom',
         fullWidth: false,
         onClick: () => {},
         labels: {
            generateLabels: (chart) => {
               return pieOptions.legendLeft(chart);
            }
         }
      },
      plugins: [{
         beforeInit: function(chart, options) {
            console.log('yolo');
         }
      }]
      rotation: 3.9,
   }
});

However, when I create the plugin using a variable, or create it inline like shown above, it doesn't log anything. The only way that I can use plugin, is when I register it globally.

Can somebody explain to me why it doesn't work?

Miterwort answered 1/6, 2017 at 13:8 Comment(1)
But look at the docs, it clearly says you can write plugin directly in chart.Miterwort
F
10

plugins should be placed in its own config section, and not nested under options.

Instead of:

options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
            generateLabels: (chart) => {
                return pieOptions.legendLeft(chart);
            }
        }
    },
    plugins: [{
        beforeInit: function(chart, options) {
            console.log('yolo');
        }
    }]
    rotation: 3.9,
}

Your code should look like:

options: {
    title: {
        display: true,
        text: graph.globals.title,
    },
    legend: {
        display: true,
        position: 'bottom',
        fullWidth: false,
        onClick: () => {},
        labels: {
        //   generateLabels: (chart) => {
        //      return pieOptions.legendLeft(chart);
        //    }
        }
    },
    rotation: 3.9,
},
plugins: [{
    beforeInit: function(chart, options) {
        console.log('yolo');
    }
}]

Working JSFiddle: https://jsfiddle.net/r1x63b8v/

Fidge answered 5/6, 2017 at 14:26 Comment(1)
This seems to have changed. Here is the latest config guidelines. chartjs.org/docs/latest/developers/plugins.htmlDerose

© 2022 - 2024 — McMap. All rights reserved.