Node JS Tutorial How To Use Event Emitter By Events Module

in #utopian-io6 years ago (edited)


Image Source

What Will I Learn?

I will learn the event emitter how to get it by the events module and how to use it with the methods ' on and emit ' , also how to use modules .

  • How to use the modules in the same directory .
  • How to define the events and util modules to get the event emitter and inherits .
  • How to use the ' on ' and ' emit ' methods to create our event emitter .

Requirements

  • Node JS must be installed on your device , you can install it From here
  • Knowledge about JavaScript language .
  • Basic Knowledge about Command Line window .
  • An editor for example notepad ++ .

Difficulty

  • Basic

Tutorial Contents

In this tutorial I am going to talk about the event emitter in node JS , firstly I want to explain what's the event before we start ..

The Events :

Everything in our computer , internet ..etc is an event for example click on some file it's an event , type on your keyboard is an event open something , close all the actions are events among these events I want to explain an event very important in Node JS ' EventEmitter ' .

Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") periodically emit named events that cause Function objects ("listeners") to be called.

  • Firstly we need to import the events module for example in Jave SE especially when we use the graphics interfaces ' Swing ' we import the events by this code import java.awt.event.*
    This package has all the events classes , the same thing in Node Js we must import it by the module ' events ' but we must make it in a variable to use it again .
    var myModule = require('events')

    to understand the modules and how to use them you can read it Node.js basic Tutorial by @sagorahmed I can add just something about modules :

    When you have two files with the extension .js I mean two node JS files and you have some functions in the first file for example and simply want to apply these functions in the second file you will use this code
    module.exports = nameOfFunction();

    But if you haven't a function and you want to create it now you must add another attribute the name like it

    module.exports.nameOfFunction = function(par){
    // something here
    };

Why I used the module.exports ?

Simply because the functions , variables ..etc are private to their own class , to be available to the other classes we must use the ' module.exports ' with the function or variable that we want to make public but the question , how to use it in other class ?

The answer is by the modules var myModule = require('./nameOfFile'); if you look at the code I used the ' ./ ' for the directory I mean it's in the same directory of my first file then the name of my file , finally we can access to our variable or function in the first file by the ' myModule . function ' .

  • Secondly The EventEmitter is a class in the module ' events ' this class has many functions among them we will use the ' on ' function let's do an example to understand exactly what it means ..

    var events = require('events');

    var myEventEmitter = new events.EventEmitter();


    Firstly as I mentioned the module ' events ' then I declared another variable myEventEmitter this variable will be an object instance from EventEmitter by this code new events.EventEmitter() I accessed by 'events' my module and the class EventEmitter to create a new object with the empty contractor without parameter .


    var events = require('events');

    var myEvent = new events.EventEmitter();

    myEvent.on('newEvent', function(msg){

    console.log(msg);

    });


    Certainly I created ' myEvent ' object to use it to access to the ' on ' function to create our custom event I specified the name of my event and what it going to do , so it has two parametrs ' name of event ' then the function I choose for example ' myEvent ' and inside the function I will just print something on our console by console.log(msg) the ' msg ' is a parameter in the function .

    The conclusion is when we emit this event the function will work and print the sentence passed by parameter .


    var events = require('events');

    var myEvent = new events.EventEmitter();

    myEvent.on('newEvent', function(msg){

    console.log(msg);

    });

    myEvent.emit('newEvent', 'This event was created');


    I used the object myEvent and I selected the ' emit ' method it has two parameters : the first is the event to activate it and the second is a message by me to give it as a ' msg ' in the function and print it , if we compare them

    myEvent.on('newEvent', function(msg)

    myEvent.emit('newEvent', 'This event was created')



    The first parameter is the name of our event to activate to trigger it and the second is a function with a parameter ' msg ' which is our message in the emit function ' This event was created ' , finally we must run it to see the result

    capture-20180319-160002.png

    This is my plugin1.js file in my desktop
    capture-20180319-160037.png
    And this is the code that I created , now we must open the command line by clicking cntrl + R and type ' cmd '

    capture-20180319-155755.png

    And I will ckeck the version of node js that I used

    capture-20180319-155836.png


    I have changed the path to the desktop by ' cd desktop ' and I am going to run my plugin1.js file by ' node plugin1 ' and look at the result :
    capture-20180319-155937.png


    To understand more I will add another example with the module ' util ' in this example I will create two instances bad engine and good engine with the price of each one let's start ..

  • Creation of modules :
    var util = require('util')

    Here I created my module with a variable named util also to get the classes into this module I will use ' inherits '

    var events = require('events')

    The same code I created the events module in this variable to create an instance from EventEmitter class with an empty constractor to get the ' on ' and ' emit ' methods

  • Creation of engine :

    var engine = function(engineCondition){

    this.engineCondition = engineCondition;

    };

    The variable engine is a function with a parameter engineCondition to be bad or good condition and it will set the value of the original value by the value passed by parameter .

  • Use the inherits method
    I used the ' util ' module to send the variable engine to the first constractor and the instance from EventEmitter as a super constractor second parameter .

  • Creation of instances from engine :


    var engineGood = new engine('a Good Engine');

    var engineBad = new engine('a Bad Engine');


    The first instance from engine with the engine condition ' good Engine ' in a variable to specify the emit method , and the second is a bad enigine with the same message but with another condition of engine ' bad ' .
    var eng = [engineGood, engineBad];

    I have created an array inside this array I have my instances with the condition to use them by forEach

  • ForEach Loop :


    eng.forEach(function(engine){

    engine.on('getEngine', function(price){

    console.log('The engine is : ' + engine.engineCondition + " And the price is : " + price);

    });

    });


    My array named ' eng ' to browse it I must use ForEach loop , inside this loop I have the function with a parameter an engine type , for this engine which is passed by parameter in the util.inherits with the event emitter I specified the ' on ' method with our event named ' getEngine ' also another function with parameter price, inside it I will print the engine is and I take the condition of my current engine in my array and the price is passed by parameter .

  • Use the emit method :

    engineGood.emit('getEngine', '1000$');
    engineBad.emit('getEngine', '100$');


    I specified the type of engine here then the method ' emit ' with two parameters , the first is our event ' getEngine ' and the second is the price as a String , the same thing with the second instance bad engine and this is all the code :

    capture-20180319-200657.png


    Then open the command line and type ' node nameOfFile '

    capture-20180319-201021.png

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.
When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and will be discarded.

You can also create your own eventEmitter class with your contractors and you can use it.

Curriculum

This is the first tutorial .



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Congratulations @alexendre-maxim! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honor on SteemitBoard.

To support your work, I also upvoted your post!
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Hey @alexendre-maxim I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • This is your first accepted contribution here in Utopian. Welcome!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 66880.67
ETH 3098.10
USDT 1.00
SBD 3.75