chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
64.36k stars 11.89k forks source link

Event listeners for plugin lifecycle methods #11200

Open alex-statsig opened 1 year ago

alex-statsig commented 1 year ago

Feature Proposal

Event listeners for plugin lifecycle methods. Rather than needing to create a "standardized" plugin object which lives within the chart ecosystem, you could easily just attach some listeners to an instance of a plugin in certain situations, and remove them imperatively. This would make it much easier to have UI separate from the chart which reflects data of the chart (ex. a custom React legend, which shows all the datasets and allows toggling).

Today it seems like chart.platform.addEventListener supports things like clicks and mouse moves, but not plugin lifecycle methods like "afterUpdate"

Possible Implementation

Simply exposing a function chart.addEventListener('afterUpdate', fn) allowing users to add listeners.

This could be hacked today by adding a custom plugin which attaches an "events" object to Chart instances, allowing callers to hook into any of the plugins methods.

stockiNail commented 1 year ago

@alex-statsig in my opinion that's good catch!!! it would simplify the life whom needs to do a simple customization to. Anyway I have some doubts about the proposal and the name of the methods because the plugin hooks as synch invocation and not event. Maybe chart.addListener('afterUpdate', fn) sounds better to me. Let me take time because I would like to submit a PR for this.

stockiNail commented 1 year ago

@alex-statsig after a first quick analysis, the proposal to add methods to add and remove listeners on the plugin hook to the chart instance, could have a limitation that you can add these listeners only after chart instance creation, therefore the first drawing will not be caught.

alex-statsig commented 1 year ago

That's fair, my usecase was centered around reacting to the data or hovered elements changing (for a custom React legend). But I can see how for usecases that want to hook into the drawing lifecycle, this wouldn't work. I think if hooking into drawing, the existing plugins works fairly well, so maybe we don't need to worry about that case

stockiNail commented 1 year ago

well, I understand. The problem is that new features like this should address many use cases and do not have constraints which reduce the usage from the users. In this case, we could add the listeners (FYI I have already done it in my private branch and it works) but it's limited on its usage and I think the community will not accept it (and could make sense it). I was also thinking to use the canvas instance as event target but the plugin hooks must be synchronously invoked because the callback can return a value needed in the chart logic/behavior. Therefore, not easy... Let me still think about it.