项目原始demo,不改动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

55 lines
2.3 KiB

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