Skip to content

Incorrect context for plugin options when scriptable #8623

Description

@stockiNail

Expected Behavior

It's a special case but could happen.
When you are accessing to a plugin (i.e. datalabels) option which has been defined as a callback, by chart.options, for instance clicking a button in the DOM, the expectation is that callback is invoked with the right context in order to have the correct value.

var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels],
    data: {
      labels: ["Jan", "Feb", "Mar", "Apr", "May"],
      datasets: [{
         label: 'dataset',
         backgroundColor: "red",
         borderColor: "red",
         data: [120, 23, 24, 45, 51]
        }]
    },
    options: {
      responsive: true,
      plugins: {
         legend: true,
         title: true,
         datalabels: {
           color: 'white',
           display(context) {
             console.log(context, context.datasetIndex);
             return true;
           }
         }
      }
    }
});
document.getElementById('randomize').addEventListener('click', function() {
  console.log(myChart.options.plugins.datalabels.display); 
});

Current Behavior

With above sample, the context passed to display callback when you click on the button is not the correct one.
If the callback is implemented to access to context properties (in this case, being datalabels, datasetIndex or dataIndex) the value are not there and then you will get an error.
The context passed is the chart context.

Here log click randomize (see codepen below).

scripOptionsBug

Steps to Reproduce

https://codepen.io/stockinail/pen/XWXgrdO

See codepen sample log.

Environment

  • Chart.js version: chart.js@3.0.0-beta.13, chartjs-plugin-datalabels@2.0.0-beta.1
  • Browser name and version: FF 86.0

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions