-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.js
62 lines (51 loc) · 788 Bytes
/
multi.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var Emitter = require('./emitter')
var yes = Symbol('yes')
module.exports = function MultiEmitter ()
{
var ems = {}
var ems_yes = {}
var keys = 0
function on (key, fn)
{
if (ems_yes[key] === yes)
{
var emitter = ems[key]
}
else
{
var emitter = ems[key] = Emitter()
ems_yes[key] = yes
keys++
}
return disposer(key, emitter.on(fn))
}
function disposer (key, ds)
{
return () =>
{
if (! ds) { return }
ds()
var emitter = ems[key]
if (emitter.is_empty())
{
delete ems[key]
delete ems_yes[key]
keys--
}
key = null
ds = null
}
}
function emit (key, ...args)
{
if (ems_yes[key] === yes)
{
ems[key].emit(...args)
}
}
function is_empty ()
{
return (! keys)
}
return { on, emit, is_empty }
}