Skip to content

Commit

Permalink
Merge branch 'master' into patch_123
Browse files Browse the repository at this point in the history
  • Loading branch information
developit committed Jun 22, 2021
2 parents ec9122b + f0f36b0 commit 53eb689
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 69 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -6,3 +6,4 @@
package-lock.json
.DS_Store
.idea
.vscode
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Jason Miller

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 13 additions & 5 deletions README.md
Expand Up @@ -80,9 +80,17 @@ emitter.off('foo', onFoo) // unlisten

### Typescript

Set `"strict": true` in your tsconfig.json to get improved type inference for `mitt` instance methods.

```ts
import mitt from 'mitt';
const emitter: mitt.Emitter = mitt();

type Events = {
foo: string
bar?: number
}

const emitter: mitt.Emitter<Events> = mitt<Events>();
```

## Examples & Demos
Expand Down Expand Up @@ -126,7 +134,7 @@ Register an event handler for the given type.

#### 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 listen for, or `"*"` for all events
- `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 listen for, or `'*'` for all events
- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event

### off
Expand All @@ -136,15 +144,15 @@ If omit the `handler`, all event handlers of the given type are deleted.

#### 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 `"*"`
- `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

### emit

Invoke all handlers for the given type.
If present, `"*"` handlers are invoked after type-matched handlers.
If present, `'*'` handlers are invoked after type-matched handlers.

Note: Manually firing "\*" handlers is not supported.
Note: Manually firing '\*' handlers is not supported.

#### Parameters

Expand Down
10 changes: 5 additions & 5 deletions package.json
Expand Up @@ -12,7 +12,7 @@
"scripts": {
"test": "npm-run-all --silent typecheck lint mocha test-types",
"mocha": "mocha test",
"test-types": "tsc test/test-types-compilation.ts --noEmit",
"test-types": "tsc test/test-types-compilation.ts --noEmit --strict",
"lint": "eslint src test --ext ts --ext js",
"typecheck": "tsc --noEmit",
"bundle": "microbundle",
Expand All @@ -34,7 +34,6 @@
],
"license": "MIT",
"files": [
"src",
"dist",
"index.d.ts"
],
Expand Down Expand Up @@ -78,7 +77,8 @@
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-non-null-assertion": 0
}
},
"eslintIgnore": [
Expand All @@ -104,6 +104,6 @@
"sinon": "^9.0.2",
"sinon-chai": "^3.5.0",
"ts-node": "^8.10.2",
"typescript": "^3.9.3"
"typescript": "^3.9.7"
}
}
}
82 changes: 54 additions & 28 deletions src/index.ts
Expand Up @@ -2,35 +2,46 @@ export type EventType = string | symbol;

// An event handler can take an optional event argument
// and should not return a value
export type Handler<T = any> = (event?: T) => void;
export type WildcardHandler = (type: EventType, event?: any) => void;
export type Handler<T = unknown> = (event: T) => void;
export type WildcardHandler<T = Record<string, unknown>> = (
type: keyof T,
event: T[keyof T]
) => void;

// An array of all currently registered event handlers for a type
export type EventHandlerList = Array<Handler>;
export type WildCardEventHandlerList = Array<WildcardHandler>;
export type EventHandlerList<T = unknown> = Array<Handler<T>>;
export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;

// A map of event types and their corresponding event handlers.
export type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;
export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<
keyof Events | '*',
EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>
>;

export interface Emitter {
all: EventHandlerMap;
export interface Emitter<Events extends Record<EventType, unknown>> {
all: EventHandlerMap<Events>;

on<T = any>(type: EventType, handler: Handler<T>): void;
on(type: '*', handler: WildcardHandler): void;
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
on(type: '*', handler: WildcardHandler<Events>): void;

off<T = any>(type: EventType, handler?: Handler<T>): void;
off(type: '*', handler: WildcardHandler): void;
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
off(type: '*', handler: WildcardHandler<Events>): void;

emit<T = any>(type: EventType, event?: T): void;
emit(type: '*', event?: any): void;
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
}

/**
* Mitt: Tiny (~200b) functional event emitter / pubsub.
* @name mitt
* @returns {Mitt}
*/
export default function mitt(all?: EventHandlerMap): Emitter {
export default function mitt<Events extends Record<EventType, unknown>>(
all?: EventHandlerMap<Events>
): Emitter<Events> {
type GenericEventHandler =
| Handler<Events[keyof Events]>
| WildcardHandler<Events>;
all = all || new Map();

return {
Expand All @@ -42,27 +53,27 @@ export default function mitt(all?: EventHandlerMap): Emitter {

/**
* Register an event handler for the given type.
* @param {string|symbol} type Type of event to listen for, or `"*"` for all events
* @param {string|symbol} type Type of event to listen for, or `'*'` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
on<T = any>(type: EventType, handler: Handler<T>) {
const handlers = all.get(type);
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) {
all.set(type, [handler]);
all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
}
},

/**
* Remove an event handler for the given type.
* If omit the `handler`, all event handlers of the given type are deleted.
* @param {string|symbol} type Type of event to unregister `handler` from, or `"*"`
* @param {Function} handler Handler function to remove
* If `handler` is omitted, all handlers of the given type are removed.
* @param {string|symbol} type Type of event to unregister `handler` from, or `'*'`
* @param {Function} [handler] Handler function to remove
* @memberOf mitt
*/
off<T = any>(type: EventType, handler?: Handler<T>) {
const handlers = all.get(type);
off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
if (handler) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
Expand All @@ -75,17 +86,32 @@ export default function mitt(all?: EventHandlerMap): Emitter {

/**
* Invoke all handlers for the given type.
* If present, `"*"` handlers are invoked after type-matched handlers.
* If present, `'*'` handlers are invoked after type-matched handlers.
*
* Note: Manually firing "*" handlers is not supported.
* Note: Manually firing '*' handlers is not supported.
*
* @param {string|symbol} type The event type to invoke
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
* @memberOf mitt
*/
emit<T = any>(type: EventType, evt: T) {
((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); });
((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); });
emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
let handlers = all!.get(type);
if (handlers) {
(handlers as EventHandlerList<Events[keyof Events]>)
.slice()
.map((handler) => {
handler(evt!);
});
}

handlers = all!.get('*');
if (handlers) {
(handlers as WildCardEventHandlerList<Events>)
.slice()
.map((handler) => {
handler(type, evt!);
});
}
}
};
}
25 changes: 18 additions & 7 deletions test/index_test.ts
@@ -1,4 +1,4 @@
import mitt, { Emitter } from '..';
import mitt, { Emitter, EventHandlerMap } from '..';
import chai, { expect } from 'chai';
import { spy } from 'sinon';
import sinonChai from 'sinon-chai';
Expand All @@ -15,17 +15,29 @@ describe('mitt', () => {
const a = spy();
const b = spy();
map.set('foo', [a, b]);
const events = mitt(map);
const events = mitt<{ foo: undefined }>(map);
events.emit('foo');
expect(a).to.have.been.calledOnce;
expect(b).to.have.been.calledOnce;
});
});

describe('mitt#', () => {
let events, inst: Emitter;

beforeEach( () => {
const eventType = Symbol('eventType');
type Events = {
foo: unknown;
constructor: unknown;
FOO: unknown;
bar: unknown;
Bar: unknown;
'baz:bat!': unknown;
'baz:baT!': unknown;
Foo: unknown;
[eventType]: unknown;
};
let events: EventHandlerMap<Events>, inst: Emitter<Events>;

beforeEach(() => {
events = new Map();
inst = mitt(events);
});
Expand Down Expand Up @@ -83,7 +95,6 @@ describe('mitt#', () => {

it('can take symbols for event types', () => {
const foo = () => {};
const eventType = Symbol('eventType');
inst.on(eventType, foo);
expect(events.get(eventType)).to.deep.equal([foo]);
});
Expand Down Expand Up @@ -151,7 +162,7 @@ describe('mitt#', () => {
it('should invoke handler for type', () => {
const event = { a: 'b' };

inst.on('foo', (one, two?) => {
inst.on('foo', (one, two?: unknown) => {
expect(one).to.deep.equal(event);
expect(two).to.be.an('undefined');
});
Expand Down

0 comments on commit 53eb689

Please sign in to comment.