stimulus-components / stimulus-chartjs

A Stimulus controller to deal with chart.js.
https://stimulus-chartjs.stimulus-components.com
MIT License
30 stars 5 forks source link

Proper way to do callbacks? #5

Open Shpigford opened 1 year ago

Shpigford commented 1 year ago

In the Chart.js docs, it gives an example of changing the format of axis labels with a callback:

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            y: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, ticks) {
                        return '$' + value;
                    }
                }
            }
        }
    }
});

How would that be used in the context of this Stimulus component?

cristi commented 1 year ago

@Shpigford did you figure out a way to pass the callback? Thanks

Shpigford commented 1 year ago

@cristi Negative. 🙁

cristi commented 1 year ago

@Shpigford I was hoping there is a better way, but this is how I ended up doing it:

import Chart from "stimulus-chartjs";
import merge from "lodash.merge";

export default class extends Chart {
  get chartOptions() {
    const yAxisCallback = {
      scales: {
        yAxes: {
          ticks: {
            callback: function(value, index, values) {
              return value.toLocaleString("en-US", { style: "currency", currency: "USD" } );
            }
          }
        }
      },
    }
    return merge(super.chartOptions, yAxisCallback);
  }
}

I'm extending the charts controller, augmenting the chartOptions and then using this controller in views. You can use the same approach if you need the currency formatting in the tooltips too.