Skip to content

Commit

Permalink
feat: Event.clear() to remove all listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
aholstenson committed Jul 28, 2019
1 parent e4cd286 commit a058c3f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,18 @@ export class Event<Parent, Args extends any[] = []> {
}
}

/**
* Clear all listeners for this event.
*/
public clear() {
this.registeredListeners = undefined;

if(this.monitor) {
// Trigger the monitor if available
this.monitor(this);
}
}

/**
* Monitor for changes to listeners. Only a single monitor is supported at
* a single time. This is intended to be used to react to if listeners are
Expand Down
31 changes: 31 additions & 0 deletions test/sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,21 @@ describe('Synchronous event', function() {
expect(triggered).toEqual(2);
});

it('clear removes all listeners', function() {
const parent = {};
const handler = new Event(parent);

let triggered = 0;
handler.subscribable(() => {
triggered++;
});

handler.clear();
handler.emit();

expect(triggered).toEqual(0);
});

it('Monitor is notified about single listener', function() {
const parent = {};
const handler = new Event(parent);
Expand Down Expand Up @@ -411,6 +426,22 @@ describe('Synchronous event', function() {
expect(triggerCount).toEqual(1);
});

it('Monitor is notified about clear', function() {
const parent = {};
const handler = new Event(parent);

handler.subscribe(() => {});

let triggerCount = 0;
handler.monitorListeners(() => {
triggerCount++;
});

handler.clear();

expect(triggerCount).toEqual(1);
});

it('listeners returns single listener', function() {
const parent = {};
const handler = new Event(parent);
Expand Down

0 comments on commit a058c3f

Please sign in to comment.