问题
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