Events and Event Emitters

Node.js is event-driven and single-threaded. It uses event loop model internally. The main single thread has an event loop that listens for all events and reacts to them. Events are bound to event handlers called listeners. Whenever an event occurs, its listener (or listeners) are called. The event-driven approach is central to Node's ability to handle high throughput on a single thread.

Many of Node's built-in modules are event based. They internally extend Event Emitter class and reacts to events such as 'error', 'data', 'connection', 'end' etc. You can also use Event Emitter class in your code to create custom events and handlers.

The Event Emitter class is part of the Node's built-in events module. To use this class in your code you have to import events module.

// Import events module
var events = require('events');

// Create an EventEmitter object called motionDetector
var motionDetector = new events.EventEmitter();

// Bind event and event handler 
motionDetector.on('motion', raiseAlarm);

// To fire the event anywhere in your code
motionDetector.emit('motion');

You can attach multiple handlers for the same event. All listeners are called synchronously in the order in which they were registered.

A listener is usually registered as:

eventEmitter.on('eventName', listener);

or

eventEmitter.addListener('eventName', listener);

Sometimes you want a listener to be invoked only once. An example of this is graceful termination process for your application. Once you listened to an event and initiated shutdown, you want to ignore further occurrences of that event. To add a listener that executes only once,

eventEmitter.once('eventName', listener);

Other useful methods of the Event Emitter class are:

Remove a listener

eventEmitter.removeListener('eventName', listener);

Remove all listeners

eventEmitter.removeAllListeners('eventName');

Add a listener to the beginning of listeners array

eventEmitter.prependListener('eventName', listener)

Instead of using an instance of Event Emitter as such, you could extend the Event Emitter class in your code to define custom methods that produce and consume events.


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.