Skip to content

Signals ​

A signal holds a value that flows read, such as the size of a dataset or the row under the pointer. A flow is built once; when a signal it read changes, only the steps that read it, and the steps that need theirs, run again, and the flow is drawn again on the next frame.

js
const random = d3.randomLcg(0.42);
const points = Array.from({length: 40}, (_, i) => ({id: i, x: random() * 100, y: random() * 100}));
const n = cm.signal(10);

const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow({transition: {duration: 600}}).renderer(renderer);

root
  .data(() => points.slice(0, n.value))
  .transform(cm.encode, {x: "x", y: "y", key: "id"})
  .transform(cm.plane)
  .add(cm.circle, {r: 5, fill: "steelblue", enter: {r: 0}, exit: {r: 0}});

root.render();
document.body.append(renderer.node());

setInterval(() => (n.value = 5 + Math.floor(random() * 35)), 1500);

Here the data reads n, so a new count runs the data again, then what needs it: the encoding, the scales, the axes and the circles. With transitions on, the circles enter, move and exit.

cm.signal(value) ​

Returns a signal holding value.

js
const n = cm.signal(10);

signal.value ​

The value of the signal. Reading it while a flow runs a step records the read. Setting it to a new value, compared with Object.is, marks the steps that read it, and those that need them, to run again, and asks their flows to render on the next frame, once for any number of changes. Setting the same value does nothing.

js
n.value; // 10
n.value = 20; // draws again what read n

What re-runs ​

A signal is read where the flow runs code as it renders, not as it's built:

  • data given as a function, such as root.data(() => points.slice(0, n.value));
  • transforms, as they run;
  • options of shapes given as functions, such as fill: (d) => (d.id === selected.value ? "red" : "gray"), and filter;
  • custom shapes as they expand, such as an axis, and primitives as they draw.

A value read as the flow is built, such as root.data(points.slice(0, n.value)) or the params of a transform, is read once: wrap it in a function.

Only a flow that has rendered is drawn again. Building it anew, as for a new frame, drops its steps, which no longer read their signals; so does flow.clear. A signal holds its readers weakly, so a chart no longer in use isn't kept by the signals it read.

Interactors, such as brushes and selections, keep their state in signals; see Interaction and the signal and crossfilter examples.