Stats

589 Contributors: 6 Wednesday, June 28, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Event Emitters

Remarks

When an event "fires" (which means the same as "publishing an event" or "emitting an event"), each listener will be called synchronously (source), along with any accompanying data that was passed in to emit(), no matter how many arguments you pass in:

myDog.on('bark', (howLoud, howLong, howIntense) => {
  // handle the event
})
myDog.emit('bark', 'loudly', '5 seconds long', 'fiercely')

The listeners will be called in the order they were registered:

myDog.on('urinate', () => console.log('My first thought was "Oh-no"'))
myDog.on('urinate', () => console.log('My second thought was "Not my lawn :)"'))
myDog.emit('urinate')
// The console.logs will happen in the right order because they were registered in that order.

But if you need a listener to fire first, before all of the other listeners that have already been added, you can use prependListener() like so:

myDog.prependListener('urinate', () => console.log('This happens before my first and second thoughts, even though it was registered after them'))

If you need to listen to an event, but you only want to hear about it once, you can use once instead of on, or prependOnceListener instead of prependListener. After the event is fired and the listener gets called, the listener will automatically be removed, and won't be called again the next time the event is fired.

Finally, if you want to remove all of the listeners and start over, feel free to do just that:

myDog.removeAllListeners()

Related Examples