galactic-bot/structure/client/EventHooker.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-04-09 16:25:06 +02:00
const EventEmitter = require('events');
2020-04-08 18:08:46 +02:00
class EventHooker {
constructor(target) {
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)) {
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;
});
});
}
}
module.exports = EventHooker;