Introduction
We would be covering Nodejs topic such as EventEmitter and module. The purpose of this article is to explain how nodejs works and how it is simply based on core Javascript concepts and how we can use these concepts to achive some functionalities and results without using any other nm or modules thus optimizing our server side code to some exten(even though modules are cached :) )
Background
For beginners please read Nodejs and Javascript, However i will try to explain the concepts. I am assuming that people are familiar with NodejS and javascript.
Using the code
Lets us contruct a small code. This code will expose EventEmitter
. We all know how event emitter works. But did we really went in detail as how event emitter really works. Lets have a look at the below code
var util = require("util");
var event = require("events").EventEmitter;
function base()
{
}
base.prototype.on = function()
{
this.emit("myEvent",func1,func2);
}
util.inherits(base,event);
var startEvent = new base();
startEvent.on("myEvent",function()
{},function()
{});
This is one of the simplest explanation provided in many books about EventEmitter. This is a great way to start.
But some times i thought why i can't use other means to achieve the same results without using core module such as "util" which does all the heavylifting. But lets look at other ways to achieve the same result with just Javascript in nodeJs.We would copy the code but this time after prototype there would be no util.inherits.
var util = require("util");
var event = require("events").EventEmitter;
function base()
{
}
base.prototype.on = function()
{
this.emit("myEvent",func1,func2);
}
base.prototype = new event;
base.prototype.constructor = event;
var startEvent = new base();
startEvent.on("myEvent",function()
{},function()
{});
As you can see this code works as expected on the server side. Another way of achieving the desired result would be as follows. This time we do not use a new keyword but rely on prototyping to do the same thing.
base.prototype = event.prototype;
base.prototype.constructor = event;
There are also other ways which are recently supported by nodejs. This is something new and further explains the concepts of inheritance in javascript. Object.create
is coming to change a lot of things needed and that can be done about Inheritance.
base.prototype = Object.create(event.prototype);
base.prototype.constructor = event;
These are some of the way we can achieve inheritance in Nodejs. However, these codes are more specific from EventEmitter pattern. This code also demonstrate various ways to achieve custome events in nodejs with different concepts borrowed from Javascipt.
The above can be put in a different module for code modularity.
Points of Interest
Please give a reading to NodejS and Javascript (EcmaScript 5) for latest development and features.