Be the first user to complete this post

  • 0
Add to List

Creating a simple event emitter using nodejs

Nodejs lets you convert any object into an event emitter by simply extending one of its classes.As far as front end is concerned, frameworks like Flux are designed around the fact that the unit of your program that manages your data is an event emitter and controllers can subscribe to listen on interesting events that the store emits. Even if you are not using flux/react, if you use webpack, you have access to all such cool nodejs utilities classes directly at the client side.

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

function DataStore() {

    // Make every instance of the data store an event emitter
    EventEmitter.call(this);

}

// Copy methods from the EventEmitter to your DataStore
util.inherits(DataStore, EventEmitter);

DataStore.prototype.save = function(data) {

    // perform an asynchronous save operation
    // ..
    // ..

    if(data){
        this.emit('change', "Saved : " + data );
    }else{
        this.emit('fail', new Error('There was an error. Nothing to save') );
    }

}

var store = new DataStore();

store.on("change", function(data) {
    console.log('Received ', data );
});

store.save("Some Data");



Also Read:

  1. Resolved - Error: listen eaccess using nodejs and pm2
  2. Configuring jshint as a pre-commit hook for your nodejs applications
  3. Configure The 'script' tag In package.json To Run Multiple Commands
  4. Unit test your Nodejs RESTful API using mocha
  5. Understanding semver versioning for your nodejs packages