events.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. import {patchEventTarget} from '../common/events';
  9. Zone.__load_patch('EventEmitter', (global: any) => {
  10. // For EventEmitter
  11. const EE_ADD_LISTENER = 'addListener';
  12. const EE_PREPEND_LISTENER = 'prependListener';
  13. const EE_REMOVE_LISTENER = 'removeListener';
  14. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  15. const EE_LISTENERS = 'listeners';
  16. const EE_ON = 'on';
  17. const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
  18. // same callback, same capture, same event name, just return
  19. return task.callback === delegate || task.callback.listener === delegate;
  20. };
  21. const eventNameToString = function(eventName: string|Symbol) {
  22. if (typeof eventName === 'string') {
  23. return eventName as string;
  24. }
  25. if (!eventName) {
  26. return '';
  27. }
  28. return eventName.toString().replace('(', '_').replace(')', '_');
  29. };
  30. function patchEventEmitterMethods(obj: any) {
  31. const result = patchEventTarget(global, [obj], {
  32. useG: false,
  33. add: EE_ADD_LISTENER,
  34. rm: EE_REMOVE_LISTENER,
  35. prepend: EE_PREPEND_LISTENER,
  36. rmAll: EE_REMOVE_ALL_LISTENER,
  37. listeners: EE_LISTENERS,
  38. chkDup: false,
  39. rt: true,
  40. diff: compareTaskCallbackVsDelegate,
  41. eventNameToString: eventNameToString
  42. });
  43. if (result && result[0]) {
  44. obj[EE_ON] = obj[EE_ADD_LISTENER];
  45. }
  46. }
  47. // EventEmitter
  48. let events;
  49. try {
  50. events = require('events');
  51. } catch (err) {
  52. }
  53. if (events && events.EventEmitter) {
  54. patchEventEmitterMethods(events.EventEmitter.prototype);
  55. }
  56. });