Simple Example of Event Emitters in Node.js

Very similar to the pub-sub or observer/listener pattern where events are triggered upon a particular action.

 

var fs = require('fs'); // get the fs module
var EventEmitterVar = require('events').EventEmitter, util = require('util');

var exampleEventEmitterClass= function () {
    console.log("emitter constructor");
}
util.inherits(exampleEventEmitterClass, EventEmitterVar);  //register class as emitter

exampleEventEmitterClass.prototype.emitMethod1 = function () {
    this.emit('emittedevent1');
} ;

exampleEventEmitterClass.prototype.emitMethod2 = function () {
    this.emit('emittedevent2');
}  ;

//register events
var evtEmitInstance = new exampleEventEmitterClass();
evtEmitInstance
    .on('emittedevent1', function () {
    console.log('Executing Event Emitter 1');
})
    .on('emittedevent2', function () {
        console.log('Executing Event Emitter 2');
    }
);

for (var i = 0; i < 3; i++) {
    evtEmitInstance.emitMethod1();
}

for (var i = 0; i < 3; i++) {
    evtEmitInstance.emitMethod2();
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s