diff options
| author | Jason Miller <[email protected]> | 2021-06-22 18:21:48 -0400 |
|---|---|---|
| committer | Jason Miller <[email protected]> | 2021-06-22 18:21:48 -0400 |
| commit | 4cce9cb6397af70498525c7b1cc829de2b21edc9 (patch) | |
| tree | 8ce02051ee44fe760687ff868ec37c76a3affe12 | |
| parent | 53eb689c83bca78d9275f724995406495262c333 (diff) | |
Add support for mitt.off("type"), which removes all handlers of a given type
| -rw-r--r-- | README.md | 4 | ||||
| -rw-r--r-- | src/index.ts | 8 |
2 files changed, 7 insertions, 5 deletions
@@ -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 diff --git a/src/index.ts b/src/index.ts index 4648156..dfc0c1f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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]>); } }, @@ -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, []); } } }, |
