Node.js - Events
In Node.js, events play a crucial role in creating asynchronous, event-driven applications.
Every action on a computer can be considered an event. For example, when a connection is established or a file is opened, these are events.
In Node.js, objects can trigger events. For instance, the readStream object emits events when opening and closing a file. Events allow you to respond to specific occurrences in your application.
EventEmitter Class
Following are the methods of the EventEmitter class −
| Sr.No. | Methods & Description |
|---|---|
| 1 |
It returns the count of listener functions listening to the event named eventName. |
| 2 |
This method returns a reference to the EventEmitter so that calls can be chained. |
| 3 |
It returns a copy of the array of listeners for the event (eventName) which we pass as a parameter. |
| 4 |
(integer) This method will return the count of listener function(s) which are listening to the event (eventName) that we pass as a parameter. |
| 5 |
It returns a reference to the EventEmitter so that calls can be chained |
| 6 |
It returns a reference to the EventEmitter so that calls can be chained. |
| 7 |
(Boolean) This method returns true if the event had listeners and false if the event doesnt have listeners. |
| 8 |
The events for which the emitter has registered listeners are returned in an array list by this method. |
| 9 |
It returns a reference to the EventEmitter so that calls can be chained |
| 10 |
It returns a copy of the listeners array for a specific event named eventName. It also returns a copy of the array of listeners for any wrappers which are created by the emitter.once() method. |
EventEmitter Class: Event Listeners Methods
Following are the event listener methods of the EventEmitter class −
| Sr.No. | Methods & Description |
|---|---|
| 1 |
emitter.addlistener(event, listener) It returns the instance of the EventEmitter to which the listener was added. |
| 2 |
It returns an event listener for a specific event. |
| 3 |
It returns an event listener for a specific event. When the specified event is emitted, the provided callback function is executed. |
EventEmitter Class: Methods to Remove Listeners
Following are the methods to remove listeners −
| Sr.No. | Methods & Description |
|---|---|
| 1 |
It returns a reference to the EventEmitter so that calls can be chained. |
| 2 |
It returns emitter, so calls can be chained. |
EventTarget Class
Following are the methods of the EventTarget class −
| Sr.No. | Methods & Description |
|---|---|
| 1 |
eventTarget.addEventListener() It returns a reference to the EventEmitter so that calls can be chained. |
| 2 |
This methods return value is false if at least one of the event handlers which are handling that specific event called Event.preventDefault() method else, it returns true. |
| 3 |
eventTarget.removeEventListener() It returns a reference to the EventEmitter so that calls can be chained. |