2020-04-16 03:19:50 +05:00
|
|
|
class EventManager {
|
|
|
|
|
constructor() {
|
|
|
|
|
this._registry = {};
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-24 11:14:16 +05:00
|
|
|
subscribeMulti(names, handler) {
|
|
|
|
|
names.forEach((name) => {
|
|
|
|
|
this.subscribe(name, handler);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-16 03:19:50 +05:00
|
|
|
subscribe(name, handler) {
|
|
|
|
|
if (!name || !handler) throw new Error("name and handler are required.");
|
2020-04-16 03:31:34 +05:00
|
|
|
if (!this._registry[name]) this._registry[name] = [];
|
2020-04-16 03:19:50 +05:00
|
|
|
this._registry[name].push(handler);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
unsubscribe(name, handler) {
|
|
|
|
|
if (!this._registry[name]) return;
|
|
|
|
|
const index = this._registry[name].indexOf(handler);
|
|
|
|
|
if (index <= -1) return;
|
|
|
|
|
this._registry[name].splice(index, 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
publish(name, ...args) {
|
|
|
|
|
if (!this._registry[name]) return;
|
|
|
|
|
const handlers = this._registry[name];
|
|
|
|
|
handlers.forEach((handler) => {
|
|
|
|
|
handler(...args);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
export default EventManager;
|