Hey Simon,
Here’s a forked version that addresses your concerns:
https://beta.observablehq.com/@jashkenas/visualisation-of-contact-networks
The best way to separate initialization from updating, within a cell, is to rely on this
. In an Observable notebook, this
is the previous value of the cell. So, for a cell that is a D3 SVG visualization, this
is undefined
the first time the cell runs, and can be the running SVG visualization on every cell re-evaluation thereafter.
Using this
, and Mike’s reference for modifying a force layout: https://bl.ocks.org/mbostock/1095795
… you wind up with a cell that reuses its own svg element, force simulation and link list, and can restart the simulation when the list of links changes.
As for the playable slider, I’ve relied on the slider’s value as the mutable source of truth, and have a little playloop as an asynchronous generator that updates the slider’s value before waiting two seconds to proceed.
There are other ways to glue this together, but this seemed like the easiest one that required minimal-ish changes to your code.
Let me know if you have any questions!