Add custom JavaScript function callback in Blazor

Viewed 124

I'm creating a Razor component to encapsulate Chart.js. The source code is on GitHub.

At the moment I create nice chart but the problem I'm facing is about the callback. To create a new chart is quite straight forward. In the page I add the component

<Chart Config="_config1" @ref="_chart1" Id="@Id1"></Chart>

and in the code, I add the configuration for a bar chart. The object BarChartConfig is converted in a json to create the chart.

_config1 = new BarChartConfig()
{
    CanvasId = Id1,
    Type = ChartType.Bar,
    Options = new Options()
    {
        Plugins = new Plugins()
        {
            Legend = new Legend()
            {
                Align = LegendAlign.Center,
                Display = false,
                Position = LegendPosition.Right
            }
        },
        Scales = new Scales()
        {
            X = new XAxes()
            {
                Stacked = true,
                Ticks = new Ticks()
                {
                    MaxRotation = 0,
                    MinRotation = 0
                }
            },
            Y = new YAxes()
            {
                Stacked = true
            }
        }
    }
};

enter image description here

What I try to do now is to add some callback or function. For example, I like to add a custom function like this one in the ticks part.

const config = {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Chart with Tick Configuration'
      }
    },
    scales: {
      x: {
        ticks: {
          // For a category axis, the val is the index so the lookup via getLabelForValue is needed
          callback: function(val, index) {
            // Hide every 2nd tick label
            return index % 2 === 0 ? this.getLabelForValue(val) : '';
          },
          color: 'red',
        }
      }
    }
  },
};

I'm pretty sure I can use JSInterop in some way to achieve that but I don't know how.

For example, how can I bind/add a JavaScript function at runtime?

Another nice thing I found is the user can click on the legend to exclude a category for the chart. How can I add a callback for this event?

0 Answers
Related