-
-
Notifications
You must be signed in to change notification settings - Fork 935
/
unhandle.ts
38 lines (32 loc) · 938 Bytes
/
unhandle.ts
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
import EventEmitter = require('events');
type Origin = EventEmitter;
type Event = string | symbol;
type Fn = (...args: unknown[]) => void;
interface Handler {
origin: Origin;
event: Event;
fn: Fn;
}
interface Unhandler {
once: (origin: Origin, event: Event, fn: Fn) => void;
unhandleAll: () => void;
}
// When attaching listeners, it's very easy to forget about them.
// Especially if you do error handling and set timeouts.
// So instead of checking if it's proper to throw an error on every timeout ever,
// use this simple tool which will remove all listeners you have attached.
export default (): Unhandler => {
const handlers: Handler[] = [];
return {
once(origin: Origin, event: Event, fn: Fn) {
origin.once(event, fn);
handlers.push({origin, event, fn});
},
unhandleAll() {
for (const handler of handlers) {
const {origin, event, fn} = handler;
origin.removeListener(event, fn);
}
}
};
};