A horrible introduction to using modern JavaScript tooling with D3
Chapter 12
Let’s say I want to add d3 to a page. It’s easy-peasy! I just add a little line to the HTML saying hey, include the JavaScript file for d3.
After we include that, we have a shiny, brand-new d3
variable to use. How exciting!
Now let’s think about adding a few JavaScript files to build some charts. Each chart gets its own JavaScript file, and each chart has its own width
. One of the charts is nice and narrow - 200 pixels - and the other one is nice and wide - 800 pixels.
chart1.js
chart2.js
Here’s the problem: if we add both files to our page, which is the real width
variable? In the same way that d3
gets shared, width
is also shared.
If we run chart1.js
first, then we run chart2.js
, everything will seem fine…. until we have to go back to chart1 again. Maybe we hovered or something? The original value of width
will be forgotten, and everything will crash to the ground and burn and it will be the biggest disaster in all of history.
This is not good.
If we were just writing normal JavaScript, I might solve it like this:
chart1.js
chart2.js
“What’s that do?” you ask. And I shudder, and I say something like “oh you know, locally scoped variables in a self-executing function” and your brain crashes to the ground and burns and it’s the second biggest disaster in all of history.
But actually instead you say “what?” and I say “hush, hush, sweet child, let us learn about build systems, and solve a lot of other problems, too” and you shrug and say, “sure, it’s all nonsense anyway,” and I shrug, and we all shrug together, and then we learn about build systems.