Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Event Emitters in node js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 371
    Comment on it

    Event emitter in node js?

    Event Emitter is a class that is in event module. Event emitter simply allows you to listen for "events" and assign actions to
    run when those event occur. If you are familiar with front end development then you will know about the keyboard and mouse events. These are very similiar, except you can emit events on you own.
    For Ex- New record saved in the database, you can emit recordSaved event.


    Using EventEmitters

    To use Event Emitter in your application you have to first import the events module, like as follows:

    var events = require('events');

    this events object has a single property, that is EventEmitter class.

    Ex:-

    var EventEmitter = require('events').EventEmitter;
    
    var ee = new EventEmitter();
    ee.on("newConnection", function() {
        console.log("New event trigger");
    });
    
    ee.emit("newConnection");

    First of we created a new object of EventEmitter class. There are 2 methods that we have used for events: on and emit

    on

    on method takes two parameters, the event we are listening for and the callback method. Here the event name we are listening for is newConnection.

    emit

    emit method's first parameter is the name of the event here it is newConnection.


    Other method of EventEmitter:

    once

    It is same as on, but it'll work only once. After being called for the first time, the listner will be removed.

    ee.once('newConnection', function() {
        console.log("I am once method of EventEmitter class.");
    });
    
    ee.emit('newConnection'); // I am once method of EventEmitter class.
    ee.emit('newConnection');

    removeAllListeners

    It removes all the listeners

    ee.removeAllListeners()

    It will remove only the specified listener:

    ee.removeAllListeners('newConnection');


    Example:-

    userModel:

     

    var util         = require("util");
    var EventEmitter = require("events").EventEmitter;
    
    var id = 1;
    var database = {
        users: [
            { id: id++, name: "Joe Smith",  occupation: "developer"    },
            { id: id++, name: "Jane Doe",   occupation: "data analyst" },
            { id: id++, name: "John Henry", occupation: "designer"     }
        ]
    };
    
    function UserList () {
        EventEmitter.call(this);
    }
    
    UserList.prototype.save = function (obj) {
        obj.id = id++;
        database.users.push(obj);
        this.emit("saved-user", obj);
    };
    
    UserList.prototype.all = function () {
        return database.users;
    };
    
    util.inherits(UserList, EventEmitter);
    
    module.exports = UserList;
    
    userController.js
    
    var UserList = require("./user");
    var users = new UserList();
    
    users.on("saved-user", function (user) {
        console.log("saved: " + user.name + " (" + user.id + ")");
        console.log(users.all())
    });
    
    
    /*
    @ Login user
    */
    exports.login = function(req, res, next) {
        users.save({ name: "Jane Doe", occupation: "manager" });
        users.save({ name: "John Jacob", occupation: "developer" })
    }
    
    
    /*
    Results:
    
    [ { id: 1, name: 'Joe Smith', occupation: 'developer' },
      { id: 2, name: 'Jane Doe', occupation: 'data analyst' },
      { id: 3, name: 'John Henry', occupation: 'designer' },
      { name: 'Jane Doe', occupation: 'manager', id: 4 },
      { name: 'John Jacob', occupation: 'developer', id: 5 } ]
    
      */

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: