stimulus-chartjs
stimulus-chartjs copied to clipboard
Proper way to do callbacks?
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 did you figure out a way to pass the callback? Thanks
@cristi Negative. 🙁
@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.