Chris Wilson
Chris Wilson

Reputation: 6719

How to have multiple d3 window resize events

I have three svg elements on one page, each chaperoned by D3. Each one has its own page-resize logic assigned by a simple module I've written to make them responsive.

The trouble is that only the last resize event is firing, as it appears to have overwritten the earlier page resize events. Is this the expected behavior of d3.select(window).on('resize', ...)? I'm accustomed to $(window).resize(...), which works fine when invoked multiple time.

I've seen this previous answer suggest that multiple resize events are possible in D3. Am I doing something dumb?

Here's a simple example I stuck on jsFiddle:

d3.select(window).on("resize", function() {
   d3.select("#d3console").append("div").html("d3 resize event A!"); 
});

d3.select(window).on("resize", function() {
   d3.select("#d3console").append("div").html("d3 resize event B!"); 
});

$(window).bind("resize", function() {
   d3.select("#jQconsole").append("div").html("jQ resize event A!"); 
});

$(window).bind("resize", function() {
   d3.select("#jQconsole").append("div").html("jQ resize event B!"); 
});

Which outputs:

d3 resize event B!
d3 resize event B!
jQ resize event A!
jQ resize event B!
jQ resize event A!
jQ resize event B!

I know one can keep shunting the previous resize functions into a chain like so. Just expected different behavior from D3.

Upvotes: 12

Views: 5187

Answers (2)

Anbu Agarwal
Anbu Agarwal

Reputation: 490

It may be a good idea to use ResizeObserver like here to have each module be able to setup / remove its own resize observer.

Upvotes: 0

Steve P
Steve P

Reputation: 19377

You need to namespace the listeners e.g. on('resize.one') and on('resize.two')

From the API Docs:

If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added. To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar".

Upvotes: 20

Related Questions