|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow |
| 8 | + */ |
| 9 | + |
| 10 | +export default class EventEmitter<Events: Object> { |
| 11 | + listenersMap: Map<string, Set<Function>> = new Map(); |
| 12 | + |
| 13 | + addListener<Event: $Keys<Events>>( |
| 14 | + event: Event, |
| 15 | + listener: (...$ElementType<Events, Event>) => any, |
| 16 | + ): void { |
| 17 | + let listeners = this.listenersMap.get(event); |
| 18 | + if (listeners === undefined) { |
| 19 | + listeners = new Set(); |
| 20 | + |
| 21 | + this.listenersMap.set(event, listeners); |
| 22 | + } |
| 23 | + |
| 24 | + listeners.add(listener); |
| 25 | + } |
| 26 | + |
| 27 | + emit<Event: $Keys<Events>>( |
| 28 | + event: Event, |
| 29 | + ...args: $ElementType<Events, Event> |
| 30 | + ): void { |
| 31 | + const listeners = this.listenersMap.get(event); |
| 32 | + if (listeners !== undefined) { |
| 33 | + let didThrow = false; |
| 34 | + let caughtError = null; |
| 35 | + |
| 36 | + listeners.forEach(listener => { |
| 37 | + try { |
| 38 | + listener.apply(null, args); |
| 39 | + } catch (error) { |
| 40 | + if (caughtError === null) { |
| 41 | + didThrow = true; |
| 42 | + caughtError = error; |
| 43 | + } |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + if (didThrow) { |
| 48 | + throw caughtError; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + removeAllListeners(event?: $Keys<Events>): void { |
| 54 | + if (event != null) { |
| 55 | + this.listenersMap.delete(event); |
| 56 | + } else { |
| 57 | + this.listenersMap.clear(); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + removeListener(event: $Keys<Events>, listener: Function): void { |
| 62 | + const listeners = this.listenersMap.get(event); |
| 63 | + if (listeners !== undefined) { |
| 64 | + listeners.delete(listener); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments