UNPKG

2.33 kBJavaScriptView Raw
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 {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.
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 * 3. Events can be emitted with at most 3 arguments. (For example: when using `emitter.emit('foo', a, b, c)`,
31 * the arguments `a`, `b`, and `c` will be passed to the listener functions.)
32 * @returns {SafeEmitter} An emitter
33 */
34module.exports = () => {
35 const listeners = Object.create(null);
36
37 return Object.freeze({
38 on(eventName, listener) {
39 if (eventName in listeners) {
40 listeners[eventName].push(listener);
41 } else {
42 listeners[eventName] = [listener];
43 }
44 },
45 emit(eventName, a, b, c) {
46 if (eventName in listeners) {
47 listeners[eventName].forEach(listener => listener(a, b, c));
48 }
49 },
50 eventNames() {
51 return Object.keys(listeners);
52 }
53 });
54};