A tiny publish / subscribe
Components talk through named channels instead of calling each other directly.
JavaScript · A tiny publish / subscribeIntermediate
function createBus() {
const handlers = new Map();
return {
on(topic, fn) {
if (!handlers.has(topic)) handlers.set(topic, new Set());
handlers.get(topic).add(fn);
return () => handlers.get(topic).delete(fn); // call it to unsubscribe
},
emit(topic, data) {
handlers.get(topic)?.forEach((fn) => fn(data));
},
};
}
const bus = createBus();
const off = bus.on('saved', (d) => console.log('saved', d));
bus.emit('saved', { id: 1 });
off();pubsubobservereventspattern