Skip to content

Commit

Permalink
Add support for mitt.off("type"), which removes all handlers of a giv…
Browse files Browse the repository at this point in the history
…en type
  • Loading branch information
developit committed Jun 22, 2021
1 parent 53eb689 commit 4cce9cb
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,12 @@ Register an event handler for the given type.
### off

Remove an event handler for the given type.
If omit the `handler`, all event handlers of the given type are deleted.
If `handler` is omitted, all handlers of the given type are removed.

#### Parameters

- `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))** Type of event to unregister `handler` from, or `'*'`
- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Handler function to remove
- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?** Handler function to remove

### emit

Expand Down
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ export default function mitt<Events extends Record<EventType, unknown>>(
*/
on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
const added = handlers && handlers.push(handler);
if (!added) {
if (handlers) {
handlers.push(handler);
}
else {
all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
}
},
Expand All @@ -79,7 +81,7 @@ export default function mitt<Events extends Record<EventType, unknown>>(
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
else {
all.delete(type);
all!.set(type, []);
}
}
},
Expand Down

0 comments on commit 4cce9cb

Please sign in to comment.