1 | /**
|
---|
2 | * @fileoverview A variant of EventEmitter which does not give listeners information about each other
|
---|
3 | * @author Teddy Katz
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | //------------------------------------------------------------------------------
|
---|
9 | // Typedefs
|
---|
10 | //------------------------------------------------------------------------------
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * An event emitter
|
---|
14 | * @typedef {Object} SafeEmitter
|
---|
15 | * @property {(eventName: string, listenerFunc: Function) => void} on Adds a listener for a given event name
|
---|
16 | * @property {(eventName: string, arg1?: any, arg2?: any, arg3?: any) => void} 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.
|
---|
19 | */
|
---|
20 |
|
---|
21 | /**
|
---|
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
|
---|
31 | */
|
---|
32 | module.exports = () => {
|
---|
33 | const listeners = Object.create(null);
|
---|
34 |
|
---|
35 | return Object.freeze({
|
---|
36 | on(eventName, listener) {
|
---|
37 | if (eventName in listeners) {
|
---|
38 | listeners[eventName].push(listener);
|
---|
39 | } else {
|
---|
40 | listeners[eventName] = [listener];
|
---|
41 | }
|
---|
42 | },
|
---|
43 | emit(eventName, ...args) {
|
---|
44 | if (eventName in listeners) {
|
---|
45 | listeners[eventName].forEach(listener => listener(...args));
|
---|
46 | }
|
---|
47 | },
|
---|
48 | eventNames() {
|
---|
49 | return Object.keys(listeners);
|
---|
50 | }
|
---|
51 | });
|
---|
52 | };
|
---|