2020-04-16 03:19:50 +05:00
|
|
|
class EventManager {
|
|
|
|
|
constructor() {
|
2021-08-08 12:20:07 +05:00
|
|
|
this._registry = new Map();
|
2020-04-16 03:19:50 +05:00
|
|
|
}
|
|
|
|
|
|
2020-09-09 11:45:42 +05:00
|
|
|
unsubscribeAll() {
|
2021-08-08 12:20:07 +05:00
|
|
|
this._registry.clear();
|
2020-09-09 11:45:42 +05:00
|
|
|
}
|
|
|
|
|
|
2020-08-24 11:14:16 +05:00
|
|
|
subscribeMulti(names, handler) {
|
|
|
|
|
names.forEach((name) => {
|
|
|
|
|
this.subscribe(name, handler);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-08 12:20:07 +05:00
|
|
|
subscribe(name, handler, once = false) {
|
2020-04-16 03:19:50 +05:00
|
|
|
if (!name || !handler) throw new Error("name and handler are required.");
|
2021-08-08 12:20:07 +05:00
|
|
|
this._registry.set(handler, { name, once });
|
2020-04-16 03:19:50 +05:00
|
|
|
}
|
|
|
|
|
|
2021-08-08 12:20:07 +05:00
|
|
|
unsubscribe(_name, handler) {
|
|
|
|
|
this._registry.delete(handler);
|
2020-04-16 03:19:50 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
publish(name, ...args) {
|
2021-08-08 12:20:07 +05:00
|
|
|
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
|
|
|
});
|
|
|
|
|
}
|
2020-11-11 15:43:09 +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);
|
|
|
|
|
});
|
|
|
|
|
|
2020-11-11 15:43:09 +05:00
|
|
|
if (handlers.length <= 0) return true;
|
2021-08-17 13:26:35 +05:00
|
|
|
return await Promise.all(handlers.map((handler) => handler(...args)));
|
2020-11-11 15:43:09 +05:00
|
|
|
}
|
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;
|