chartist-js / chartist

Simple responsive charts
https://chartist.dev
MIT License
13.34k stars 2.53k forks source link

[Feature request] Make it possible to disable chart redraw on window resize #1218

Closed wujekbogdan closed 4 years ago

wujekbogdan commented 4 years ago

Currently, the window resize listener is hardcoded. I'd like to take over the control and re-initialize the chart on my own, for example, using the ResizeObserver API, so It would be great if there was an option that would allow for disabling the window resize event.

wujekbogdan commented 4 years ago

I found a workaround.

The resize listener is exposed by the Chartist instance so it is possible to detach the listener:

const chartist = new Chartist.Line(el, data, options);

setTimeout(() => {
  window.removeEventListener('resize', chartist.resizeListener, false);
}, 1);

I'm not sure why setTimeout is needed, but without it, the listener is not removed.

gionkunz commented 4 years ago

setTimeout is needed because the initial rendering a thus also resize listener will be defered a separate task into the event loop using setTimeout. Therefore, you'd need to wait for chartist be be created first. Maybe this would be a safer option:

const chartist = new Chartist.Line(el, data, options).on('created', () => {
  window.removeEventListener('resize', chartist.resizeListener, false);
});

If you don't care about the options provider being detached from the media query listeners (only important if you're using responsive configuration overrides), you could also do this more API safe method of calling detach:

const chartist = new Chartist.Line(el, data, options);
chartist.on('created', () => {
  chartist.detach();
  // Attach custom scheduler which calls chartist.update();
});
wujekbogdan commented 4 years ago

Thank you, I'll follow the first path because, as you say, the .detach() method not only removes the resize listener but also calls removeMediaQueryListeners() - which I'd like to avoid.