Skip to content

listenersCount & newListener event #32

Description

@xamgore

Hi! Node.js v0.1.26 implemented a special event newListener. It is emitted once any new listener is added to an EventEmitter. It seems to me that dest.on(...) should trigger source to emit newListener event. In the example below the code prints nothing:

const ee1 = new EventEmitter()
const ee2 = new EventEmitter()

ee1.once('newListener', (event, listener) => console.log('ee1 new listener'))
ee2.once('newListener', (event, listener) => console.log('ee2 new listener'))

propagate(ee1, ee2)

// should print:
// ee1 new listener
// ee2 new listener
ee2.on('event', (a, b) => console.log('got propagated event', a, b))

I faced the issue while propagating MongoDB change streams into Node's EventEmitter. As you can see in the code, ChangeStream extends EventEmitter and calls emit method only if newListener was fired. In other words, there must be at least one event listener registered. listenerCount also has to be changed.

this.on('newListener', eventName => {
  if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) {
    this.cursor.on('data', change => processNewChange(this, change));
  }
});

What do you think about it?

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions