-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
67 lines (57 loc) · 1.68 KB
/
index.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
63
64
65
66
67
'use strict'
function propagateKeyedEvents(keyedEventNames, source, dest) {
const keyedListeners = {}
Object.entries(keyedEventNames).forEach(([srcEventName, dstEventName]) => {
keyedListeners[srcEventName] = (...args) => {
dest.emit(dstEventName, ...args)
}
})
Object.entries(keyedListeners).forEach(([srcEventName, listener]) => {
source.on(srcEventName, listener)
})
return {
end() {
Object.entries(keyedListeners).forEach(([srcEventName, listener]) => {
source.removeListener(srcEventName, listener)
})
},
}
}
function propagateAllEvents(source, dest) {
const oldEmit = source.emit
// Returns true if the event had listeners, false otherwise.
// https://nodejs.org/api/events.html#events_emitter_emit_eventname_args
source.emit = (eventName, ...args) => {
const oldEmitHadListeners = oldEmit.call(source, eventName, ...args)
const destEmitHadListeners = dest.emit(eventName, ...args)
return oldEmitHadListeners || destEmitHadListeners
}
return {
end() {
source.emit = oldEmit
},
}
}
module.exports = function propagate(events, source, dest) {
if (arguments.length < 3) {
dest = source
source = events
events = undefined
}
if (events === undefined) {
return propagateAllEvents(source, dest)
}
let keyedEventNames
if (Array.isArray(events)) {
keyedEventNames = {}
events.forEach(eventName => {
keyedEventNames[eventName] = eventName
})
} else if (typeof events === 'object') {
keyedEventNames = events
} else {
const eventName = events
keyedEventNames = { [eventName]: eventName }
}
return propagateKeyedEvents(keyedEventNames, source, dest)
}