Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Creating a simple event emitter using nodejs

Nodejs lets you con­vert any object into an event emit­ter by sim­ply extend­ing one of its classes.As far as front end is con­cerned, frame­works like Flux are designed around the fact that the unit of your pro­gram that man­ages your data is an event emit­ter and con­trollers can sub­scribe to lis­ten on inter­est­ing events that the store emits.

Even if you are not using flux/react, if you use web­pack, you have access to all such cool nodejs util­i­ties 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");

Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.

You may also like...