NodeJS_Unit_6

Event

An event, in a computing context, is an action or occurrence that can be identified by a program and has significance (impact) for system hardware or software. Events can be user-generated, such as keystrokes and mouse clicks, or system-generated, such as program loading, running out of memory and errors.

Event Driven Programming

• Node.js uses event driven programming. It means as soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur. It is the one of the reason why Node.js is pretty fast compared to other similar technologies.
• There is a main loop in the event driven application that listens for events, and then triggers a callback function when one of those events is detected.
• The working of event driven programming depends upon events.
• Events are monitored by a code known as Event Listener.
• If the event Listener detect that assigned event has occurred, it will trigger a callback function known as an event handler, which will perform event.


Difference between Events and Callbacks:

Although, Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern.

Steps:

EventEmitter class to bind event and event listener:

    // Import events module
    var events = require('events');

    // Create an eventEmitter object
    var eventEmitter = new events.EventEmitter();

    To bind event handler with an event:
    // Bind event and even handler as follows
    eventEmitter.on('eventName', eventHandler);

    To fire an event:
    // Fire an event
    eventEmitter.emit('eventName');

    Example:
    // Import events module
    var events = require('events');
    var eventEmitter = new events.EventEmitter();

    // Create an event handler as follows
    var connectHandler = function connected() {
    console.log('connection succesful.');

    // Fire the data_received event
    eventEmitter.emit('data_received');
    }

    // Bind the connection event with the handler
    eventEmitter.on('connection', connectHandler);

    // Bind the data_received event with the anonymous function
    eventEmitter.on('data_received', function(){
    console.log('data received succesfully.');
    });

    // Fire the connection event
    eventEmitter.emit('connection');
    console.log("Program Ended.");


6.1 Event Emitter class

• Node.js allows us to create and handle custom events easily by using events module.
• Event module includes EventEmitter class which can be used to raise and handle custom events.
• NodeJS has multiple in-built events available through event module & EventEmitter class.
• EventEmitter can be accessible by using following code:
    // Import events module
    var events = require ('events');

    // Create an eventEmitter object
    var eventEmitter = new events.EventEmitter ();
• EventEmitter gives us multiple properties like ON and EMIT. The ON property is used to bind a function with the event & EMIT is used to call the event.

Important methods of EventEmitter class:

EventEmitter Methods Description
addListener(event, listener) Adds a listener to the end of the listeners array for the specified event.
on(event, listener) Adds a listener to the end of the listeners array for the specified event.
once(event, listener) Adds a one-time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
removeListener(event, listener) Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
removeAllListeners([event]) Removes all listeners, or those of the specified event.
setMaxListeners(n) By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
getMaxListeners() Returns the current maximum listener value for the emitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.


Example:
    // importing events
    const EventEmitter = require('events');
    var eventEmitter = new EventEmitter ();

    // registering to myEvent
    eventEmitter.on ('myEvent', (msg) => {
    console.log (msg);
    });

    // triggering myEvent
    eventEmitter.emit('myEvent', "First event");


6.2 Returning event emitter

• When we are returning from EventEmitter we used a constructor function returns an EventEmitter object.
• This EventEmitter object can be used to subscribe for the events.

Example:
    var emitter = require('events').EventEmitter;
    function LoopProcessor(num) {
    var e = new emitter();
    setTimeout(function () {

    for (var i = 1; i <= num; i++) {
    e.emit('BeforeProcess', i);
    console.log('Processing number:' + i);
    e.emit('AfterProcess', i);
    }
    }
    , 2000)

    return e;
    }
    var lp = LoopProcessor(3);

    lp.on('BeforeProcess', function (data) {
    console.log('About to start the process for ' + data);
    });

    lp.on('AfterProcess', function (data) {
    console.log('Completed processing ' + data);
    });



6.3 Inhering events or Extend EventEmitter Class

• We can extend the constructor function from EventEmitter class to emit the events.

• Example:
    var emitter = require('events').EventEmitter;
    var util = require('util');

    function LoopProcessor(num) {
    var me = this;
    setTimeout(function () {
    for (var i = 1; i <= num; i++) {
    me.emit('BeforeProcess', i);
    console.log('Processing number:' + i);
    me.emit('AfterProcess', i);
    }
    }
    , 2000)

    return this;
    }

    util.inherits(LoopProcessor, emitter)

    var lp = new LoopProcessor(3);

    lp.on('BeforeProcess', function (data) {
    console.log('About to start the process for ' + data);
    });

    lp.on('AfterProcess', function (data) {
    console.log('Completed processing ' + data);
    });

No comments:

Post a Comment