-
Notifications
You must be signed in to change notification settings - Fork 2
/
EventHandler.js
39 lines (32 loc) · 1018 Bytes
/
EventHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"use strict";
const Log = require('./Log.js');
class EventHandler {
constructor(name) {
this.name = name || 'unknown';
this._listeners = [];
}
subscribe(callback) {
if (this._listeners.indexOf(callback) !== -1) {
Log.info("[Skip] Listener already subscribed");
}
this._listeners.push(callback);
}
remove(callback) {
this._listeners = this._listeners.filter(c => c !== callback);
}
async emit(...args) {
for (var i = 0; i < this._listeners.length; i++) {
const callback = this._listeners[i];
if (typeof callback === 'function') {
try {
await callback(...args);
} catch (e) {
Log.info('Error handling event: ' + this.name);
Log.debug(args);
Log.error(e, false); // note prevent notification spamming
}
}
}
}
}
module.exports = EventHandler;