diff --git a/README.md b/README.md index 0219f3a..b81629b 100644 --- a/README.md +++ b/README.md @@ -130,10 +130,12 @@ const emitter: Emitter = mitt(); - [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 @@ -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. diff --git a/src/index.ts b/src/index.ts index 17672aa..987728b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,12 @@ export interface Emitter> { on(type: Key, handler: Handler): void; on(type: '*', handler: WildcardHandler): void; + once( + type: Key, + handler: Handler + ): void; + once(type: '*', handler: WildcardHandler): void; + off( type: Key, handler?: Handler @@ -38,6 +44,9 @@ export interface Emitter> { ): void; } +const onceHandlerKey = '__mittOnce'; +const onceHandlerMarker = {}; + /** * Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt @@ -49,6 +58,10 @@ export default function mitt>( type GenericEventHandler = | Handler | WildcardHandler; + type OnceHandlerMetadata = { + marker: typeof onceHandlerMarker; + handler: GenericEventHandler; + }; all = all || new Map(); return { @@ -72,6 +85,44 @@ export default function mitt>( } }, + /** + * 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(type: Key, handler: GenericEventHandler) { + let fired = false; + const wrapper = ((...args: Array) => { + // 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 | undefined = all!.get(type); + if (handlers) { + handlers.splice(handlers.indexOf(wrapper) >>> 0, 1); + } + (handler as (...args: Array) => void)(...args); + }) 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 | undefined = all!.get(type); + if (handlers) { + handlers.push(wrapper); + } else { + all!.set(type, [wrapper] as EventHandlerList); + } + }, + /** * Remove an event handler for the given type. * If `handler` is omitted, all handlers of the given type are removed. @@ -83,7 +134,35 @@ export default function mitt>( const handlers: Array | 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, []); } diff --git a/test/index_test.ts b/test/index_test.ts index 31c9495..ef70944 100644 --- a/test/index_test.ts +++ b/test/index_test.ts @@ -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', () => { @@ -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#', () => { @@ -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'); diff --git a/test/test-types-compilation.ts b/test/test-types-compilation.ts index 476e631..b59e609 100644 --- a/test/test-types-compilation.ts +++ b/test/test-types-compilation.ts @@ -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 */