mirror of
https://github.com/livebook-dev/livebook.git
synced 2024-11-17 21:33:16 +08:00
266bf35bd0
* Show all sections and enable cross-section focus navigation * Move focus to the client * Add shortcut for evaluating all cells * Fix and expand tests * Make section links scroll to the given section
50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
/**
|
|
* A basic pub-sub implementation for client-side communication.
|
|
*/
|
|
export default class PubSub {
|
|
constructor() {
|
|
this.subscribersByTopic = {};
|
|
}
|
|
|
|
/**
|
|
* Links the given function to the given topic.
|
|
*
|
|
* Subsequent calls to `broadcast` with this topic
|
|
* will result in this function being called.
|
|
*/
|
|
subscribe(topic, callback) {
|
|
if (!Array.isArray(this.subscribersByTopic[topic])) {
|
|
this.subscribersByTopic[topic] = [];
|
|
}
|
|
|
|
this.subscribersByTopic[topic].push(callback);
|
|
}
|
|
|
|
/**
|
|
* Unlinks the given function from the given topic.
|
|
*
|
|
* Note that you must pass the same function reference
|
|
* as you passed to `subscribe`.
|
|
*/
|
|
unsubscribe(topic, callback) {
|
|
const idx = this.subscribersByTopic[topic].indexOf(callback);
|
|
|
|
if (idx !== -1) {
|
|
this.subscribersByTopic[topic].splice(idx, 1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calls all functions linked to the given topic
|
|
* and passes `payload` as the argument.
|
|
*/
|
|
broadcast(topic, payload) {
|
|
if (Array.isArray(this.subscribersByTopic[topic])) {
|
|
this.subscribersByTopic[topic].forEach((callback) => {
|
|
callback(payload);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
export const globalPubSub = new PubSub();
|