-
Notifications
You must be signed in to change notification settings - Fork 8
/
events.js
43 lines (40 loc) · 1.14 KB
/
events.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
const async = require('async');
function EventSource(obj) {
this.listeners = {};
this.listeneriter = 0;
obj.listen = (signal, callback) => this.listen(signal, callback);
obj.unlisten = (signal, lid) => this.unlisten(signal, lid);
obj.sig = (signal, args) => this.sig(signal, args);
}
EventSource.prototype = {
listen(signal, callback) {
this.listeneriter++;
if (!this.listeners[signal]) this.listeners[signal] = [];
const r = {};
r[this.listeneriter] = callback;
this.listeners[signal].push(r);
return this.listeneriter;
},
unlisten(signal, lid) {
delete this.listeners[signal][lid];
},
sig(signal, args, cb) {
const kv = this.listeners[signal];
if (!kv) return cb ? cb() : null;
const v = Object.values(kv);
if (!v) return cb ? cb() : null;
async.eachSeries(
v,
(val, asyncCallback) => {
if (val)
val(args, asyncCallback);
else
asyncCallback();
},
cb
);
},
};
module.exports = {
EventSource,
};