I'm writing a custom plugin for Chart.js 4
and I want my plugin to behave well with the chartjs-plugin-zoom
plugin.
In order to do this, I need to listen to the chartjs-plugin-zoom
events (onZoomStart
, onZoom
, etc.) from inside my plugin.
How would I do this without interfering with other chart/plugin functionality?
I've tried to do this in my plugin:
afterInit(chart: Chart<ChartType>, args: EmptyObject, options: AnyObject) {
chart.options.plugins.zoom.zoom.onZoom = (context) => {
//my custom logic
}
}
which works, but the problem is that it is overriding all other event handlers set by the Chart's options or other plugins.
Is there a more "proper" way to do this?
Basically in any javascript appliaction/library, you can simply "wrap" functions (there obviously some caveats).
But basically you "remember" to old function "do your thing", and "call the old function" (link to the documentation for the call
function, for some details on the parameters needed).
How this could look like:
afterInit(chart: Chart<ChartType>, args: EmptyObject, options: AnyObject) {
// remember the function
let initialFunction = chart.options.plugins.zoom.zoom.onZoom;
chart.options.plugins.zoom.zoom.onZoom = (context) => {
// do your thing
// your custom logic
// call the old function ( with the zoom-object as "this" )
initialFunction.call( chart.options.plugins.zoom.zoom, context );
}
}
You can also call first the old functionen and than call you custom code, it's in your hands.
That said, maybe chartjs has a better solution out-of-the-box. as @kikon pointed out.
In general it is always better to use standard conventions or/and event passing, than wrapping function, for various reasons. I just wanted to share an alternate approach, which works in may similar situations.