Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 788
Chris Wilson Avatar asked Oct 16 '14 16:10

Chris Wilson


1 Answers

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".

like image 130
explunit Avatar answered Oct 07 '22 14:10

explunit