The Event Emitter Pattern in Node

As we move forward in our journey to learn Node's internals, one of the most important and widely used (but not understood) concept is that of EventEmitter.

What is an EventEmitter?
An Event Emitter pattern is the one in which there are 2 or more objects - the Event Emitter, and the Event Listeners. The Emitter 'emits' and event - broadcasting that an event has occured - and the listeners then act accordingly. This is also called the publisher-subscriber pattern.

Continuation Passing Style (CPS)
CPS is where the function 'returns' by calling another callback function that was provided to it as an argument - i.e., when a function is finished doing it's work, it calls the callback function along with any resultant data as an argument to the callback function. Technically, it does not 'return', however, it passes the control to the next stage of processing. This is called the CPS.


Continuation Passing Style (CPS) v/s EventEmitter
There are different use cases for each of the styles, but in general:
-Use CPS when you want to regain control at the end of the processing of a large function
-Use EventEmitter whenever a number of events will be raised and need to be consumed.


Event Types
An object can emit multiple types of events; the event types are typically lowercase words without a space. E.g. "data", "end", etc. The emitter can also pass one or more arguments along with the emitted event, which will be received by the listeners.

Creating an Event Emitter
An Event Emitter object can be created by inheriting from the EventEmitter class. Then, that object can use the emit function to emit events.

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var Ticker = function() {
    //this is a Ticker class
    setInterval(function() {
        this.emit("tick", "sample_arg");
    }.bind(this), 1000)
}

util.inherits(Ticker, EventEmitter);

var t = new Ticker();
t.on("tick", function(arg) {
    console.log("Tick, arg: " + arg);
})



In the above example, Ticker is our class which inherits from the EventEmitter. It then proceeds to send a tick event, along with a sample_arg, every second.
Also, we are using the .on() function to register an event handler, which will get called whenever the tick event is raised. It will also be passed the sample_arg.

Functions of EventEmitter
The EventEmitter class has a number of functions that are used to attach/detach the event handlers. They are:
1) .on(type, callback): Attach an event handler (callback) to the event of type type.
2) .once(type, callback): Attach an event handler which will be called only once for one type of event,
3) .removeListener(type, function_name): Remove the listener named function_name from the listeners listening to type event. This mandates that you specify a named callback while attaching the listener.
4) .removeAllListeners(type): Remove all listeners of type type.

No comments:

Post a Comment