简体   繁体   中英

How to call a function on 'load' event in D3?

Apologies for my Javascript inexperience. I am a JavaScript and D3 newbie, trying to adapt the subway wait assessment example from Mike Dewar's Getting Started with D3 book .

As given, the example loads with none of the subway lines plotted -- you will have to click one to plot it. I thought it would be simple to change the code so that, when the visualization starts up, one of the lines (say the "A" line) is already plotted by default.

I can do this by copying and pasting part of the code from inside the get_timeseries_data function in Dewar's script (which does some checks and calls a draw_timeseries function). But this seems wrong. The point of writing a function is that I should be able to call get_timeseries_data itself directly, no?

Since Dewar's final code chunk there uses selection.on('click'), it seemed logical to mimic this but using .on('load') instead:

d3.select('#Line_A_key')
  .on('load', get_timeseries_data);

Adding this to the end of the script does not work. It doesn't even give an error in the console, so I guess the 'load' event just never happens -- why?

So I thought maybe I can just call the get_timeseries_data function directly without waiting for a 'load' event:

d3.select('#Line_A_key')
  .get_timeseries_data();

But this complains that the object has no method 'get_timeseries_data'. Okay, this is true, but begs the question -- when can I call a function in D3?

D3 (or is it all of JS?) seems to have certain situations where it expects a function that takes data and index as its parameters. How do I learn what these situations are? And if I already have a function in this form, can I also call it outside of these situations, or do I need to write a whole new function for other cases?

I haven't been able to answer these questions for myself from browsing the D3 API, or from any of several online tutorials, and most unfortunately not from Dewar's book either. Where should I have looked instead?

#Line_A_key may not be loaded. So you can't select it...

d3.select(window).on("load", get_timeseries_data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM