Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
fix: fluent interface for EventEmitter (#475)
Browse files Browse the repository at this point in the history
  • Loading branch information
jtmalinowski authored and mhevery committed Nov 3, 2016
1 parent 21935e8 commit c5130a6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
17 changes: 10 additions & 7 deletions lib/node/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@

import {makeZoneAwareAddListener, makeZoneAwareListeners, makeZoneAwareRemoveListener, patchMethod} from '../common/utils';

const callAndReturnFirstParam = (fn: (self: any, args: any[]) => any) => {
return (self: any, args: any[]) => {
fn(self, args);
return self;
};
};

// For EventEmitter
const EE_ADD_LISTENER = 'addListener';
Expand All @@ -16,12 +22,9 @@ const EE_REMOVE_LISTENER = 'removeListener';
const EE_LISTENERS = 'listeners';
const EE_ON = 'on';


const zoneAwareAddListener =
makeZoneAwareAddListener(EE_ADD_LISTENER, EE_REMOVE_LISTENER, false, true);
const zoneAwarePrependListener =
makeZoneAwareAddListener(EE_PREPEND_LISTENER, EE_REMOVE_LISTENER, false, true);
const zoneAwareRemoveListener = makeZoneAwareRemoveListener(EE_REMOVE_LISTENER, false);
const zoneAwareAddListener = callAndReturnFirstParam(makeZoneAwareAddListener(EE_ADD_LISTENER, EE_REMOVE_LISTENER, false, true));
const zoneAwarePrependListener = callAndReturnFirstParam(makeZoneAwareAddListener(EE_PREPEND_LISTENER, EE_REMOVE_LISTENER, false, true));
const zoneAwareRemoveListener = callAndReturnFirstParam(makeZoneAwareRemoveListener(EE_REMOVE_LISTENER, false));
const zoneAwareListeners = makeZoneAwareListeners(EE_LISTENERS);

export function patchEventEmitterMethods(obj: any): boolean {
Expand All @@ -46,4 +49,4 @@ try {

if (events && events.EventEmitter) {
patchEventEmitterMethods(events.EventEmitter.prototype);
}
}
6 changes: 6 additions & 0 deletions test/node/events.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ describe('nodejs EventEmitter', () => {
zoneB.run(() => emitter.emit('test', 'test value'));
expect(expectZoneACount).toBe(2);
});
it('allows chaining methods', () => {
zoneA.run(() => {
expect(emitter.on('test', expectZoneA)).toBe(emitter);
expect(emitter.addListener('test', expectZoneA)).toBe(emitter);
});
});
it('should remove listeners properly', () => {
zoneA.run(() => {
emitter.on('test', shouldNotRun);
Expand Down

0 comments on commit c5130a6

Please sign in to comment.