Published unlisted
Edited
Jul 25, 2021
1 star
Insert cell
Insert cell
pubsub = {
const target = new EventTarget(),
teardown = p => (!p ? invalidation : Promise.race([invalidation, p])),
subscribe = (name, handler, invalidated) => {
target.addEventListener(name, handler);
teardown(invalidated).then(() => target.removeEventListener(name, handler));
},
unsubscribe = (name, handler) => {
target.removeEventListener(name, handler);
},
publish = (name, data) => {
target.dispatchEvent(new CustomEvent(name, { detail: data }));
};

return { subscribe, unsubscribe, publish };
}
Insert cell
pubsub.publish('update', now/1000|0)
Insert cell
{
const foo = html`<output>`;
let n = 0;
pubsub.subscribe('update', ({detail: data}) => {
foo.value = `${n++}: ${data}`;
}, invalidation);
return foo;
}
Insert cell
pubsub.subscribe(
'update',
(() => {
let last;
return ({detail: d}) => d !== last && pubsub.publish('updatefiltered', last = d);
})(),
invalidation
)
Insert cell
{
const foo = html`<output>`;
let n = 0;
pubsub.subscribe('updatefiltered', ({detail: data}) => {
foo.value = `${n++}: ${data}`;
}, invalidation);
return foo;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more