Skip to content

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

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to Node.js documentation.eventsIssues and PRs related to EventEmitter and the events module.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions