🏠 back to Observable

is there a way to generate a cell template

Dear Observable team,

I have one svg divided equally by 9 square cells. Each cell draws exactly the same stuff based on a single graph data structure. They differ only in a dependency to its own start (x, y) position. Is it able to create a cell template so the change made in one cell can reflect on all cells?

As there is no way to create a cell template, instead of creating and updating each of 9 cells manually, i created a nodeGroup (to initialise visual) and a nodeGroupObserver (to update visual on drag) cells which declares only one visual stuff. I made it depend on “initCellCloneConfig” and “updateCellCloneConfig”, respectively. Whenever there is a drag event the config generates iterable promises.

Example: https://observablehq.com/d/66a62a5cbbf0ac2c

Thanks for your time :grinning:

Most commonly if you want to reuse code for multiple cells you would define a function cell and then call that function from the other cells. For example, this notebook defines a ramp function that renders a color interpolator to a canvas:

And similarly this notebook defines a drag function which binds d3.drag to a d3.forceSimulation:

In general we recommend functions over cells that have side-effects (such as a cell that reaches into an SVG element defined by another cell and mutates its contents) because it’s usually easier to understand when side-effects occur if you apply them explicitly by calling a function rather than relying on implicit re-evaluation of cells. (Try to avoid mutation.)