stimulus-chartjs icon indicating copy to clipboard operation
stimulus-chartjs copied to clipboard

Proper way to do callbacks?

Open Shpigford opened this issue 2 years ago • 3 comments

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?

Shpigford avatar Feb 28 '23 21:02 Shpigford

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

cristi avatar Mar 11 '23 16:03 cristi

@cristi Negative. 🙁

Shpigford avatar Mar 11 '23 16:03 Shpigford

@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.

cristi avatar Mar 11 '23 17:03 cristi