How to have multiple d3 window resize events

2019-04-05 02:10发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-05 02:27

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

查看更多
虎瘦雄心在
3楼-- · 2019-04-05 02:42

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

查看更多
登录 后发表回答