2020-04-09 16:25:06 +02:00
|
|
|
const EventEmitter = require('events');
|
2020-04-08 18:08:46 +02:00
|
|
|
|
|
|
|
class EventHooker {
|
|
|
|
|
|
|
|
constructor(target) {
|
2020-05-21 12:47:58 +02:00
|
|
|
if(!(target instanceof EventEmitter)) TypeError('Invalid EventEmitter passed to EventHooker.');
|
2020-04-08 18:08:46 +02:00
|
|
|
|
|
|
|
this.target = target;
|
|
|
|
this.events = new Map();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
hook(eventName, func) {
|
|
|
|
if(this.events.has(eventName)) {
|
|
|
|
const funcs = this.events.get(eventName);
|
|
|
|
this.events.set(eventName, [ ...funcs, func ]);
|
|
|
|
} else {
|
|
|
|
this.events.set(eventName, [ func ]);
|
|
|
|
this._handleEvent(eventName);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unhook(eventName, func) {
|
|
|
|
if(this.events.has(eventName)) {
|
2020-05-21 12:47:58 +02:00
|
|
|
const funcs = this.events.get(eventName);
|
2020-04-08 18:08:46 +02:00
|
|
|
const index = funcs.indexOf(func);
|
|
|
|
if(index > -1) {
|
|
|
|
funcs.splice(index, 1);
|
|
|
|
this.events.set(eventName, funcs);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async _handleEvent(eventName) {
|
|
|
|
this.target.on(eventName, (...args) => {
|
|
|
|
this.events.get(eventName).forEach(async (f) => {
|
|
|
|
const result = f(...args);
|
|
|
|
if(f instanceof Promise) await result;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-05-21 12:47:58 +02:00
|
|
|
module.exports = EventHooker;
|