Node event module

Node.js event module provides EventEmitter class

ThiseventsThe module provides us with the EventEmitter class, which is the key to handling events in Node.

I published a complete article, So here I will only describe the API without further explaining how to use the API.

const EventEmitter = require('events')
const door = new EventEmitter()

The event listener eats its own dog food and uses the following events:

  • newListenerWhen adding a listener
  • removeListenerWhen the listener is deleted

This is a detailed description of the most useful method:

emitter.addListener()

Aliasemitter.on().

emitter.emit()

Issue events. It calls each event listener synchronously in the order in which the events are registered.

emitter.eventNames()

Return an array of strings that represent the events registered on the current EventListener:

door.eventNames()

emitter.getMaxListeners()

Gets the maximum number of listeners that can be added to the EventListener object. The listener defaults to 10, but it can be increased or decreased by usingsetMaxListeners()

door.getMaxListeners()

emitter.listenerCount()

Get the listener count of the event passed as a parameter:

door.listenerCount('open')

emitter.listeners()

Get an array of listeners for the event passed as a parameter:

door.listeners('open')

emitter.off()

Aliasemitter.removeListener() added in Node 10

emitter.on()

Add a callback function that is called when an event is emitted.

usage:

door.on('open', () => {
  console.log('Door was opened')
})

emitter.once()

Add a callback function that is called when the event is issued for the first time after registering for this event. This callback will only be called once and will not be called again.

const EventEmitter = require('events')
const ee = new EventEmitter()

ee.once(‘my-event’, () => { //call callback function once })

emitter.prependListener()

When you use add listeneronoraddListener, It is added to the end of the listener queue and is called the end. useprependListenerIt is added and called before other listeners.

emitter.prependOnceListener()

When you use add listeneronce, It is added to the end of the listener queue and is called the end. useprependOnceListenerIt is added and called before other listeners.

emitter.removeAllListeners()

Delete all the listeners of the event emitter object that listen to a specific event:

door.removeAllListeners('open')

emitter.removeListener()

Remove the specific listener. You can achieve this by saving the callback function in a variable (after adding it) so that you can refer to it later:

const doSomething = () => {}
door.on('open', doSomething)
door.removeListener('open', doSomething)

emitter.setMaxListeners()

Set the maximum number of listeners that can be added to the EventListener object. The listener defaults to 10, but it can be increased or decreased.

door.setMaxListeners(50)

Download mine for freeNode.js manual


More node tutorials: