2 * @fileoverview A variant of EventEmitter which does not give listeners information about each other
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
14 * @typedef {Object} SafeEmitter
15 * @property {function(eventName: string, listenerFunc: Function): void} on Adds a listener for a given event name
16 * @property {function(eventName: string, arg1?: any, arg2?: any, arg3?: any)} emit Emits an event with a given name.
17 * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments.
18 * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners.
22 * Creates an object which can listen for and emit events.
23 * This is similar to the EventEmitter API in Node's standard library, but it has a few differences.
24 * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without
25 * letting the modules know about each other at all.
26 * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when
27 * another module throws an error or registers a listener.
28 * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a
29 * `this` value of the emitter instance, which would give listeners access to other listeners.)
30 * @returns {SafeEmitter} An emitter
32 module.exports = () => {
33 const listeners = Object.create(null);
35 return Object.freeze({
36 on(eventName, listener) {
37 if (eventName in listeners) {
38 listeners[eventName].push(listener);
40 listeners[eventName] = [listener];
43 emit(eventName, ...args) {
44 if (eventName in listeners) {
45 listeners[eventName].forEach(listener => listener(...args));
49 return Object.keys(listeners);