Skip to content
Open
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
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,12 @@ const emitter: Emitter<Events> = mitt<Events>();
- [all](#all)
- [on](#on)
- [Parameters](#parameters)
- [off](#off)
- [once](#once)
- [Parameters](#parameters-1)
- [emit](#emit)
- [off](#off)
- [Parameters](#parameters-2)
- [emit](#emit)
- [Parameters](#parameters-3)

### mitt

Expand All @@ -154,6 +156,17 @@ Register an event handler for the given type.
- `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

### once

Register an event handler for the given type that is invoked at most once.
The handler is removed after its first invocation, and can also be
removed beforehand with `off(type, handler)`.

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

### off

Remove an event handler for the given type.
Expand Down
81 changes: 80 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ export interface Emitter<Events extends Record<EventType, unknown>> {
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
on(type: '*', handler: WildcardHandler<Events>): void;

once<Key extends keyof Events>(
type: Key,
handler: Handler<Events[Key]>
): void;
once(type: '*', handler: WildcardHandler<Events>): void;

off<Key extends keyof Events>(
type: Key,
handler?: Handler<Events[Key]>
Expand All @@ -38,6 +44,9 @@ export interface Emitter<Events extends Record<EventType, unknown>> {
): void;
}

const onceHandlerKey = '__mittOnce';
const onceHandlerMarker = {};

/**
* Mitt: Tiny (~200b) functional event emitter / pubsub.
* @name mitt
Expand All @@ -49,6 +58,10 @@ export default function mitt<Events extends Record<EventType, unknown>>(
type GenericEventHandler =
| Handler<Events[keyof Events]>
| WildcardHandler<Events>;
type OnceHandlerMetadata = {
marker: typeof onceHandlerMarker;
handler: GenericEventHandler;
};
all = all || new Map();

return {
Expand All @@ -72,6 +85,44 @@ export default function mitt<Events extends Record<EventType, unknown>>(
}
},

/**
* Register an event handler for the given type that is invoked at most once.
* The handler is removed after its first invocation, and can also be
* removed beforehand with `off(type, handler)`.
* @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
*/
once<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
let fired = false;
const wrapper = ((...args: Array<unknown>) => {
// emit() invokes handlers from a snapshot, so when an
// earlier listener re-emits synchronously the nested emit
// would invoke this wrapper and the outer emit would invoke
// it again. Guard on `fired` so it runs at most once.
if (fired) {
return;
}
fired = true;
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
handlers.splice(handlers.indexOf(wrapper) >>> 0, 1);
}
(handler as (...args: Array<unknown>) => void)(...args);
Comment on lines +109 to +111

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard once wrappers against nested emit snapshots

When an earlier listener synchronously re-emits the same event before the once() listener is reached, the nested emit() invokes and removes this wrapper, but the outer emit() still invokes it from its .slice() snapshot. Consequently, a single once('foo', fn) registration calls fn twice; wildcard listeners have the same problem. Track and check a per-wrapper fired flag before invoking the handler, rather than relying solely on removal from the live map.

Useful? React with πŸ‘Β / πŸ‘Ž.

}) as GenericEventHandler;
// Store the handler on its wrapper so emitters sharing a map
// can identify it without requiring WeakMap.
Object.defineProperty(wrapper, onceHandlerKey, {
value: { marker: onceHandlerMarker, handler }
});
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
handlers.push(wrapper);
} else {
all!.set(type, [wrapper] as EventHandlerList<Events[keyof Events]>);
}
},

/**
* Remove an event handler for the given type.
* If `handler` is omitted, all handlers of the given type are removed.
Expand All @@ -83,7 +134,35 @@ export default function mitt<Events extends Record<EventType, unknown>>(
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
if (handler) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
// A handler registered via `once()` is stored as a wrapper,
// so match it through the original handler. Like Node's
// `removeListener`, the first matching listener is removed.
// A plain loop (no Array.prototype.findIndex) keeps this
// working on IE11, within the README's advertised IE9+
// support.
let index = -1;
for (let i = 0; i < handlers.length; i++) {
const listener = handlers[i];
if (listener !== handler) {
const descriptor: PropertyDescriptor | undefined =
typeof listener === 'function'
? Object.getOwnPropertyDescriptor(listener, onceHandlerKey)
: undefined;
const metadata: OnceHandlerMetadata | undefined = descriptor
? descriptor.value
: undefined;
if (
!metadata ||
metadata.marker !== onceHandlerMarker ||
metadata.handler !== handler
) {
continue;
}
}
index = i;
break;
}
handlers.splice(index >>> 0, 1);
} else {
all!.set(type, []);
}
Expand Down
157 changes: 157 additions & 0 deletions test/index_test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import mitt, { Emitter, EventHandlerMap } from '..';
import chai, { expect } from 'chai';
import { readFileSync } from 'fs';
import { spy } from 'sinon';
import sinonChai from 'sinon-chai';
import { runInNewContext } from 'vm';
chai.use(sinonChai);

describe('mitt', () => {
Expand All @@ -20,6 +22,29 @@ describe('mitt', () => {
expect(a).to.have.been.calledOnce;
expect(b).to.have.been.calledOnce;
});

it('should work with Map available but no WeakMap', () => {
const source = readFileSync(require.resolve('..'), 'utf8');
const loadMitt = runInNewContext(source + '\nmodule.exports;', {
Map,
WeakMap: undefined,
module: { exports: {} }
}) as typeof mitt;
const emitter = loadMitt<{ foo: undefined }>();
const other = loadMitt(emitter.all);
const listener = spy();
const cancelled = spy();

emitter.on('foo', listener);
emitter.once('foo', cancelled);
other.off('foo', cancelled);
other.emit('foo');
other.off('foo', listener);
other.emit('foo');

expect(listener).to.have.been.calledOnce;
expect(cancelled).to.not.have.been.called;
});
});

describe('mitt#', () => {
Expand Down Expand Up @@ -157,6 +182,138 @@ describe('mitt#', () => {
});
});

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

it('should invoke handler only once', () => {
const foo = spy();
inst.once('foo', foo);
inst.emit('foo');
inst.emit('foo');
expect(foo).to.have.been.calledOnce;
});

it('should pass the event to the handler', () => {
const event = { a: 'b' };
const foo = spy();
inst.once('foo', foo);
inst.emit('foo', event);
expect(foo).to.have.been.calledOnce.and.calledWith(event);
});

it('should invoke * handlers only once', () => {
const star = spy();
inst.once('*', star);
inst.emit('foo', 'a');
inst.emit('bar', 'b');
expect(star).to.have.been.calledOnce.and.calledWith('foo', 'a');
});

it('should allow removing a once handler with off() before it fires', () => {
const foo = spy();
inst.once('foo', foo);
inst.off('foo', foo);
inst.emit('foo');
expect(foo).to.not.have.been.called;
});

it('should remove the once handler even if it throws', () => {
const foo = spy(() => {
throw new Error('boom');
});
inst.once('foo', foo);
expect(() => inst.emit('foo')).to.throw('boom');
inst.emit('foo');
expect(foo).to.have.been.calledOnce;
});

it('should remove the first matching listener when combined with on()', () => {
// `on` first, then `once`: off() removes the `on` registration,
// so the `once` handler still fires exactly once.
const foo = spy();
inst.on('foo', foo);
inst.once('foo', foo);
inst.off('foo', foo);
inst.emit('foo');
inst.emit('foo');
expect(foo).to.have.been.calledOnce;
});

it('should remove the once handler first when it was registered first', () => {
// `once` first, then `on`: off() removes the `once` handler,
// so the `on` registration keeps firing.
const foo = spy();
inst.once('foo', foo);
inst.on('foo', foo);
inst.off('foo', foo);
inst.emit('foo');
inst.emit('foo');
expect(foo).to.have.been.calledTwice;
});

it('should invoke handler only once when an earlier listener re-emits', () => {
// The outer emit() keeps a snapshot of the handlers, so without
// a fired guard the wrapper is invoked once by the nested emit
// and once more by the outer emit.
const foo = spy();
let reemitted = false;
inst.on('foo', () => {
if (!reemitted) {
reemitted = true;
inst.emit('foo');
}
});
inst.once('foo', foo);
inst.emit('foo');
expect(foo).to.have.been.calledOnce;
});

it('should invoke * handlers only once when an earlier listener re-emits', () => {
const star = spy();
let reemitted = false;
inst.on('*', () => {
if (!reemitted) {
reemitted = true;
inst.emit('foo', 'a');
}
});
inst.once('*', star);
inst.emit('foo', 'a');
expect(star).to.have.been.calledOnce.and.calledWith('foo', 'a');
});

it('should allow removing a once handler through an emitter sharing the map', () => {
// `mitt(existingMap)` shares the handler map, so off() must
// resolve the once() wrapper through shared metadata, not
// through state private to the registering emitter.
const foo = spy();
const other = mitt(events);
inst.once('foo', foo);
other.off('foo', foo);
inst.emit('foo');
expect(foo).to.not.have.been.called;
});

it('should remove handlers without Array.prototype.findIndex', () => {
// IE11 (within the README's advertised IE9+ support) has no
// Array.prototype.findIndex, so off() must not rely on it.
const foo = spy();
const findIndex = Array.prototype.findIndex;
// @ts-expect-error testing an environment without findIndex (IE11)
Array.prototype.findIndex = undefined;
try {
inst.on('foo', foo);
inst.off('foo', foo);
inst.emit('foo');
} finally {
Array.prototype.findIndex = findIndex;
}
expect(foo).to.not.have.been.called;
});
});

describe('emit()', () => {
it('should be a function', () => {
expect(inst).to.have.property('emit').that.is.a('function');
Expand Down
19 changes: 19 additions & 0 deletions test/test-types-compilation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ const wildcardHandler = (
emitter.on('*', barHandler);
}

/*
* Check that 'once' args are inferred correctly
*/
{
// @ts-expect-error
emitter.once('foo', barHandler);
emitter.once('foo', fooHandler);

emitter.once('bar', barHandler);
// @ts-expect-error
emitter.once('bar', fooHandler);

emitter.once('*', wildcardHandler);
// fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string
emitter.once('*', fooHandler);
// @ts-expect-error
emitter.once('*', barHandler);
}

/*
* Check that 'off' args are inferred correctly
*/
Expand Down