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

  1. TimothyGu commented on Jul 3, 2018

    @TimothyGu
    Member

    I think maybe a "FIFO" logic is better for this case.

    Can you explain why you think so?

  2. added
    eventsIssues and PRs related to EventEmitter and the events module.
    on Jul 3, 2018
  3. pandaGao commented on Jul 4, 2018

    @pandaGao
    Author

    To remove a listener we need to "find" it. Like array.find() I consider this "find action" is from start to end at first. At least document doesn't indicate current "LIFO" logic in removeListener(), it could be confused when someone meet the same case like my example. Of course it only make a difference if you add multiple same listeners with on() and once() at the same time. Perhaps we could update the document to point it out.

  4. TimothyGu commented on Jul 4, 2018

    @TimothyGu
    Member

    At this point, I'd say the easier thing to do is to update the documentation rather than making a semver-major change.

  5. added
    docIssues and PRs related to Node.js documentation.
    on Jul 4, 2018
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