angular/packages/zone.js/lib/node/events.ts
Doug Parker 7c1991048b refactor(zone.js): wrap Zone.__load_patch calls in exported functions (#53443)
This removes top-level side effects from each of these files and drops the dependency on global `Zone`, instead allowing it to be provided to each patch as a parameter.

Most of these are pure mechanical transformations. A couple notable files which were somewhat unique:

* `async-test.ts`, `fake-async-test.ts`, and `wtf.ts` had unique IIFE usage and patch `Zone` itself. This removes the IIFE and exports the function instead.
* `jest.ts` and `jasmine.ts` have a unique `jest` global usage which needs to be declared.

PR Close #53443
2024-03-15 18:11:33 -07:00

68 lines
2 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {patchEventTarget} from '../common/events';
import {ZoneType} from '../zone-impl';
export function patchEvents(Zone: ZoneType): void {
Zone.__load_patch('EventEmitter', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
// For EventEmitter
const EE_ADD_LISTENER = 'addListener';
const EE_PREPEND_LISTENER = 'prependListener';
const EE_REMOVE_LISTENER = 'removeListener';
const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
const EE_LISTENERS = 'listeners';
const EE_ON = 'on';
const EE_OFF = 'off';
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
// same callback, same capture, same event name, just return
return task.callback === delegate || task.callback.listener === delegate;
};
const eventNameToString = function(eventName: string|Symbol) {
if (typeof eventName === 'string') {
return eventName;
}
if (!eventName) {
return '';
}
return eventName.toString().replace('(', '_').replace(')', '_');
};
function patchEventEmitterMethods(obj: any) {
const result = patchEventTarget(global, api, [obj], {
useG: false,
add: EE_ADD_LISTENER,
rm: EE_REMOVE_LISTENER,
prepend: EE_PREPEND_LISTENER,
rmAll: EE_REMOVE_ALL_LISTENER,
listeners: EE_LISTENERS,
chkDup: false,
rt: true,
diff: compareTaskCallbackVsDelegate,
eventNameToString: eventNameToString
});
if (result && result[0]) {
obj[EE_ON] = obj[EE_ADD_LISTENER];
obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
}
}
// EventEmitter
let events;
try {
events = require('events');
} catch (err) {
}
if (events && events.EventEmitter) {
patchEventEmitterMethods(events.EventEmitter.prototype);
}
});
}