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

40 lines
964 B
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) {
if (!this._registry[name]) return true;
const handlers = this._registry[name];
if (handlers.length <= 0) return true;
return await Promise.all(handlers.map((h) => h.handler(...args)));
}
2020-04-16 03:19:50 +05:00
}
export default EventManager;