Node.js Working With Events and Event Emitter 03

Video Tutorial

Overview

Events are a simple way to manage app states and exchange data between different app components, and they are very necessary for asynchronous apps since we are using node.js we need to use the events system for better performance and easier app data management.

What are Events

So basically Events are type of handlers that get executed once some process is done or on error, which means on a state change, that will allow us to exchange data between the event trigger and the handler (Event Callback) which is a function handler some operation once this event is submitted, so we emit (submit) an event then we listen for it, when we emit and no listeners are available for that particular event, nothing is going to happen and our program gonna keep executing without problems (Normally).

So to recap this, Events are submitted using the emit method when some operations are completed (for ex: todo task is completed) and listen to that event by adding a handler that will execute once this event is submitted, it is very simple.

Using EventEmitter

So node js has a built it Event System that will allow you to emit and listen for events (custom or prebuilt) on your app.

Node.js has a built-in standard module called events and has an EventEmitter Object that will allow us to manipulate custom events

//Import the Standard Events and EventEmitter Modules 
const events = require('events');
const EventEmitter = events.EventEmitter; ///< that what we will need

And we can Instantiate an Object Of EventEmitter that we can use to submit and listen to events

//Create a New Instance
var evntEmit = new EventEmitter();
//You can Now Listen for an Event 
evntEmit.on('newEvnt', function(){
   console.log('newEvnt is Triggered Yay!');
});
//And emit the Event for triggering the handler
evntEmit.emit('newEvnt');
/* OUTPUT: newEvnt is Triggered Yay! */

And as you can see that it is very simple to trigger and listen for events but this may not clarify the whole point of events since we can achieve the same result without having to use events, I totally understand you, so let me explain this in more better way using this store example, of having a store of use data then we submit a custom event (unique) once a piece of users’ data change in order to manipulate it

//We use ES6 Class Syntax 
class Store extends EventEmitter {
  init(name, job) {
    this.name = name;
    this.job = job;
    //Emit the Initialized Event 
    //When you extend from EventEmitter Class you can use this to access the emit and on methods
    this.emit('store-init', this.name); ///< we emit store-init event and pass in the current name
  }

  getFullName() {
    return this.name;
  }

  getJob() {
    return this.job;
  }

  setName(name) {
    this.name = name;
    this.emit('name-changed', this.name);
  }

  setJob(job) {
    this.job = job;
  }

}

let pokemonsStore = new Store();
pokemonsStore.init('pikachou', 'Shoots an electric spark');
//We add the Handler for store-init event 
pokemonsStore.on('store-init', (name) => {
  //Now we can receive the name (data) that we have passed to this
  console.log('Store Initialized ', name);
});
//Also we can add listen for change event
pokemonsStore.on('name-changed', (newName) => {
  console.log('Name Changed to ', newName);
});
//We test for Asynchronous Call 
console.log('Printed Before the Last name-changed Event, haha!');1
//We trigger the Event by changin the Name
pokemonsStore.setName('bulbasaur');
//You should get
/* Store Initialized pikachou 
   Printed Before the Last name - changed Event, haha!
   Name Changed to bulbasaur
*/

The above store example should briefly explain how events work and why they are very useful and very easy to use for figuring out different app states and which one get called before the other, for more advanced usage you can practise that by implementing a complicated apps with a different states and value that will make more sense of using events.

What’s Next

So that was a very basic tutorial explaining why you should use events in your app and why they are super easy and useful for as a Web/Desktop Developer.

In the Next Tutorial, we will cover the basics of the filesystem and the node’s standard modules for reading, writing and getting specific information about a certain file.

No Comments Yet