forked from harriedegroot/nl.hdg.mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventHandler.js
48 lines (41 loc) · 1.28 KB
/
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
40
41
42
43
44
45
46
47
48
"use strict";
const Log = require('./Log');
class EventHandler {
constructor(name) {
this.name = name || 'unknown';
this._listeners = [];
this._once = new Set();
}
subscribe(callback, once) {
if (this._listeners.indexOf(callback) !== -1) {
Log.info("[Skip] Listener already subscribed");
}
this._listeners.push(callback);
if (once) {
this._once.add(callback);
}
}
unsubscribe(callback) { return this.remove(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 {
if (this._once.has(callback)) {
this.remove(callback);
this._once.delete(callback);
}
await callback(...args);
} catch (e) {
Log.info('Error handling event: ' + this.name);
Log.debug(args);
Log.error(e);
}
}
}
}
}
module.exports = EventHandler;