Sunday, August 18, 2013

How to create your own EventEmitter in NodeJS in 3 Steps

Note: This post does not seek to explain what the EventEmitter is.  For that, look at Node's site.  I'm going to show you how to make your custom object into one.  This is handy for many reasons.  I recently created a node module which wraps grunt and exposes the output from it as an EventEmitter.


Step 1: Bring in the modules


// events contains the EventEmitter 
// class we will inherit from
var events = require('events');
// and util contains `inherit` which 
// we will use to set up our object's inheritance
var util = require('util');

Step 2: Construct your class, followed by the EventEmitter's

You will want to call the EventEmitter's constructor at the end of your own.  It's standard practice when inheriting from another class that you call into the parent's constructor in order to preserve any functionality within it.  I've excluded it before, and it's not the end of the world, it just sets some default properties.  You can see what the constructor in Node does on Github.

var MyClass = function () {
    // Your class' constructor magic

    // Call the EventEmitter constructor
    events.EventEmitter.call(this);
}

Step 3: Set up the prototypal inheritance

util.inherits(MyClass, events.EventEmitter);

Well that was easy.  What this does is set up the prototype chain for us.  You can read more about the util.inherits again on Node's website.

The Final Code

var util = require("util");
var events = require("events");

function MyClass() {
    // Your class' constructor magic

    events.EventEmitter.call(this);
}

util.inherits(MyClass, events.EventEmitter);

MyClass.prototype.emitTest = function(data) {
    this.emit("data", data);
}

// Consumption

var instance = new MyClass();
instance.on('data', function (msg) {
    console.log(msg);
});

instance.emitTest("Hello World"); //=> Hello World