Skip to content

Commit

Permalink
fix: multiple same-event "once" listeners should all be called (#16)
Browse files Browse the repository at this point in the history
Co-authored-by: Artem Zakharchenko <[email protected]>
  • Loading branch information
come25136 and kettanaito authored Apr 11, 2023
1 parent c1d67df commit b5da3bf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ export class Emitter<Events extends EventMap> {
private _getListeners<EventName extends keyof Events>(
eventName: EventName
): Array<Listener<Array<unknown>>> {
return this.events.get(eventName) || []
// Always return a copy of the listeners array
// so they are fixed at the time of the "_getListeners" call.
return Array.prototype.concat.apply([], this.events.get(eventName)) || []
}

private _removeListener<EventName extends keyof Events>(
Expand All @@ -81,6 +83,9 @@ export class Emitter<Events extends EventMap> {
listener.apply(this, data)
}

// Inherit the name of the original listener.
Object.defineProperty(onceListener, 'name', { value: listener.name })

return onceListener
}

Expand Down
24 changes: 24 additions & 0 deletions test/Emitter/once.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,27 @@ it('can have multiple once listeners for different events', () => {
expect(emitter.listenerCount('hello')).toBe(0)
expect(emitter.listenerCount('goodbye')).toBe(0)
})

it('emits multiple "once" event of the same name', () => {
const emitter = new Emitter<Events>()
const firstHelloListener = jest.fn()
const secondHelloListener = jest.fn()

Object.defineProperty(firstHelloListener, 'name', {
value: 'firstHelloListener',
})
Object.defineProperty(secondHelloListener, 'name', {
value: 'secondHelloListener',
})

emitter.once('hello', firstHelloListener)
emitter.once('hello', secondHelloListener)

emitter.emit('hello', 'John')

expect(firstHelloListener).toHaveBeenCalledTimes(1)
expect(firstHelloListener).toHaveBeenCalledWith('John')

expect(secondHelloListener).toHaveBeenCalledTimes(1)
expect(secondHelloListener).toHaveBeenCalledWith('John')
})

0 comments on commit b5da3bf

Please sign in to comment.