Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const emitter: mitt.Emitter = mitt();
- [Parameters](#parameters-1)
- [emit](#emit)
- [Parameters](#parameters-2)
- [clear](#clear)

### mitt

Expand Down Expand Up @@ -142,6 +143,12 @@ Note: Manually firing "\*" handlers is not supported.
- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** The event type to invoke
- `evt` **Any?** Any value (object is recommended and powerful), passed to each handler

### clear

Remove all event handlers.

Note: This will also remove event handlers passed via `mitt(all: EventHandlerMap)`.

## Contribute

First off, thanks for taking the time to contribute!
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export interface Emitter {

emit<T = any>(type: EventType, event?: T): void;
emit(type: '*', event?: any): void;

clear(): void;
}

/** Mitt: Tiny (~200b) functional event emitter / pubsub.
Expand Down Expand Up @@ -73,6 +75,15 @@ export default function mitt(all?: EventHandlerMap): Emitter {
emit(type: EventType, evt: any) {
((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); });
((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); });
},

/**
* Remove all event handlers.
*
* Note: This will also remove event handlers passed via `mitt(all: EventHandlerMap)`.
*/
clear() {
all.clear();
}
};
}
18 changes: 18 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,22 @@ describe('mitt#', () => {
expect(star).to.have.been.calledOnce.and.calledWith('bar', eb);
});
});

describe('clear()', () => {
it('should be a function', () => {
expect(inst)
.to.have.property('clear')
.that.is.a('function');
});

it('should remove existing handlers', () => {
const foo = () => {};
const bar = () => {};
inst.on('foo', foo);
inst.on('bar', bar);
inst.clear();
expect(events.get('foo')).to.be.undefined;
expect(events.size).to.equal(0);
});
});
});