Inline plugin doesn't work

半腔热情 提交于 2019-12-12 22:35:18

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/44308458/inline-plugin-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!