Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline plugin doesn't work

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?

like image 970
Skjal Avatar asked Jun 01 '17 13:06

Skjal


1 Answers

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/

like image 184
Tot Zam Avatar answered Sep 29 '22 10:09

Tot Zam