-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
events.js
67 lines (54 loc) · 1.61 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
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'
const EventEmitter = require('events').EventEmitter
const helper = require('./helper')
function bufferEvents (emitter, eventsToBuffer) {
const listeners = []
const eventsToReply = []
function genericListener () {
eventsToReply.push(Array.from(arguments))
}
eventsToBuffer.forEach((eventName) => {
const listener = genericListener.bind(null, eventName)
listeners.push(listener)
emitter.on(eventName, listener)
})
return function () {
listeners.forEach((listener, i) => {
emitter.removeListener(eventsToBuffer[i], listener)
})
eventsToReply.forEach((args) => {
EventEmitter.prototype.emit.apply(emitter, args)
})
listeners.length = 0
eventsToReply.length = 0
}
}
class KarmaEventEmitter extends EventEmitter {
bind (object) {
for (const method in object) {
if (method.startsWith('on') && helper.isFunction(object[method])) {
this.on(helper.camelToSnake(method.slice(2)), function () {
// We do not use an arrow function here, to supply the caller as this.
object[method].apply(object, Array.from(arguments).concat(this))
})
}
}
}
emitAsync (name) {
// TODO(vojta): allow passing args
// TODO(vojta): ignore/throw if listener call done() multiple times
let pending = this.listeners(name).length
const deferred = helper.defer()
this.emit(name, () => {
if (!--pending) {
deferred.resolve()
}
})
if (!pending) {
deferred.resolve()
}
return deferred.promise
}
}
exports.EventEmitter = KarmaEventEmitter
exports.bufferEvents = bufferEvents