Skip to content

Commit

Permalink
feat(eventemitter): add clear method to EventEmitter
Browse files Browse the repository at this point in the history
add clear method to EventEmitter which enables deleting events and all its subscribed callbacks
  • Loading branch information
bencelaszlo committed Oct 2, 2024
1 parent 658e4f0 commit 261c3fd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/EventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,21 @@ export class EventEmitter {
/**
* @param {string} eventName
* @param {Array<any>} args
* @returns void
*/
emit(eventName: string, ...args: Array<any>): void {
this.subscriptions
.get(eventName)
.forEach(({ callback }) => callback(...args));
}
/**
*
* @param eventName eventName to be deleted
* @returns void
*/
clear(eventName: string): void {
this.subscriptions = new Subscriptions(
[...this.subscriptions].filter(([key]) => key !== eventName)
);
}
}
15 changes: 15 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,19 @@ describe('eventEmitter', () => {
expect(testCallbackB).toHaveBeenCalled();
expect(testCallbackB).toHaveBeenCalledWith(mockEventArgs);
});

it('should not call callbacks after an event has been deleted', () => {
const testCallbackA = jest.fn();
const testCallbackB = jest.fn();

const eventEmitter = new EventEmitter();
eventEmitter.subscribe('test-event', testCallbackA);
eventEmitter.subscribe('test-event', testCallbackB);

eventEmitter.clear('test-event');
eventEmitter.emit('test-event');

expect(testCallbackA).not.toHaveBeenCalled();
expect(testCallbackB).not.toHaveBeenCalled();
});
});

0 comments on commit 261c3fd

Please sign in to comment.