How to restructure app such that it reacts on window resize events?


I created a single-page app containing d3 chart (area chart + scatter chart combo). The area chart is static (but should react on window resize events) that serves as a background for the scatter chart that is updated whenever the mongo collection changes. So far, i made the scatter plot react using the following structure.

Template.chart.onRendered( function() {
var height = window.innerHeight;
var width = window.innerWeight;

// d3 stuff to create area chart

// d3 stuff to update scatter chart

I know that the onRendered is only called once, but is possible to force re-rendering on window resize event? Or, how do I restructure this app such that the chart rerenders itself on window resize event but minimize the redrawing of the background chart?

Thanks in advance!


Thanks, works perfectly!

I prefer this pattern:

const onWindowResize = function() {
  const width = $(window).width();
  const height = $(window).height();
  doSomethingCool(width, height);

const throttledOnWindowResize = _.throttle(onWindowResize, 200, {
  leading: false
}); {
}); {
  $(window).off('resize', throttledOnWindowResize);

It’s a bit more explicit and lets you throttle the resize events so they’re only fired once every n milliseconds.

1 Like

You can probably just use a basic abstraction like this.

// client/window.js  or something.

import $ from "jQuery";
import {Template} from "meteor/templating";

export function addWindowEvents(templateName, eventMap) {
  const template = Template[templateName];
  Object.entries(eventMap).forEach((event, handler) => {
    template.onRendered(() => $(window).on(event, handler));
    template.onDestroyed(() => $(window).off(event, handler));