Files
notesnook/packages/core/utils/event-manager.js

50 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-04-16 03:19:50 +05:00
class EventManager {
constructor() {
this._registry = new Map();
2020-04-16 03:19:50 +05:00
}
unsubscribeAll() {
this._registry.clear();
}
2020-08-24 11:14:16 +05:00
subscribeMulti(names, handler) {
names.forEach((name) => {
this.subscribe(name, handler);
});
}
subscribe(name, handler, once = false) {
2020-04-16 03:19:50 +05:00
if (!name || !handler) throw new Error("name and handler are required.");
this._registry.set(handler, { name, once });
2020-04-16 03:19:50 +05:00
}
unsubscribe(_name, handler) {
this._registry.delete(handler);
2020-04-16 03:19:50 +05:00
}
publish(name, ...args) {
this._registry.forEach((props, handler) => {
if (props.name === name) handler(...args);
if (props.once) this._registry.delete(handler);
2020-04-16 03:19:50 +05:00
});
}
async publishWithResult(name, ...args) {
2021-08-17 13:26:35 +05:00
const handlers = [];
this._registry.forEach((props, handler) => {
if (props.name === name) handlers.push(handler);
if (props.once) this._registry.delete(handler);
});
if (handlers.length <= 0) return true;
2021-08-17 13:26:35 +05:00
return await Promise.all(handlers.map((handler) => handler(...args)));
}
2021-08-31 12:11:46 +05:00
remove(...names) {
this._registry.forEach((props, handler) => {
if (names.includes(props.name)) this._registry.delete(handler);
});
}
2020-04-16 03:19:50 +05:00
}
export default EventManager;