A pub/sub bus in 50 lines
LINK subscribes a cell to a topic. BIND publishes a message. Listeners fire on every subscriber. Open this page in two tabs โ they share the bus (in the cloud) or run separately (in localStorage).
01Subscribe
Pick a topic and a callback cell. New messages on the topic will land in the cell.
02Publish
03Live feed
No messages yet. Subscribe and publish to see them flow.
04Subscriptions
| Topic | Subscriber cell | Messages received |
|---|---|---|
| No subscriptions yet. | ||
05The source
const sub = new Substrate();
function subscribe(topic, cell) {
if (!sub.has(cell)) sub.bind(cell, []);
sub.link(cell, topic, 'subscribes');
}
function publish(topic, message) {
for (const [cellName, cell] of sub.cells) {
for (const linkKey of sub.links.keys()) {
if (linkKey.startsWith(`${cellName}|${topic}|`)) {
const next = [...(cell.value || []), { topic, message, t: sub.t }];
sub.bind(cellName, next);
}
}
}
sub.tick();
}
06Take it with you
Save the bus state. Open this page in two tabs. Subscribe in tab A. Publish in tab B. If both tabs are loaded from the same cloud save, the bus becomes a real shared substrate.