Skip to content

events: Loop forwards to find listener in removeListener function #21635

Closed
@pandaGao

Description

@pandaGao

removeListener() in events module loop backwards to find listener from array. Consider the following code:

const EventEmitter = require('events')

function pong () {
  console.log('pong')
}

let a = new EventEmitter()

a.once('ping', pong)
a.on('ping', pong)
a.removeListener('ping', pong)
a.emit('ping')
a.emit('ping')

// output:
// pong

let b = new EventEmitter()

b.on('ping', pong)
b.once('ping', pong)
b.removeListener('ping', pong)
b.emit('ping')
b.emit('ping')

// output:
// pong
// pong

The output shows that for multiple same listeners, the last added one will be the first to remove (LIFO). I think maybe a "FIFO" logic is better for this case. And I find the commit on 5 Mar 2013 which implements "loop backwards" logic.
3e64b56#diff-71dcd327d0ca067b490b22d677f81966
The commit message shows this logic optimize removeAllListeners().But it did effect this specific case. Maybe removeAllListeners() should keep "LIFO" logic and the backward loop optimizing, and removeListener() could use a forward loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.eventsIssues and PRs related to the events subsystem / EventEmitter.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions