Tapping the power of Node.js: EventEmitters

Assigning events to objects in Node.js can be done with Node’s Events and Util modules. This gives the developer the ability to create a very complex chain of events that can be assigned to a very complex chain of objects. Simple events can also be assigned without these two modules with JavaScript. JavaScript lets one assign a function to an HTML element (like a button, as shown below). In this code, a button element is assigned a function. When the the button is clicked the AddPerson( ) function is called and the name “Mary” is displayed on the screen.

The onclick JavaScript example provides a basis for understanding the EventEmiiter class in the Node.js event module. However, EventEmitter is a little more complicated. It is a five step process:

  • Import the Node.js events module
  • Instantiate an EventEmitter Object
  • Create an Event Handler
  • Assign a Trigger Name and the Event Handler to the EventEmitter Object (using the event “on” method)
  • Trigger the EventEmitter object with the EventEmitter “emit” method. This can be considered similar to the onclick method in JavaScript. However, you don’t need to click anything.

After you import the Events module into your Node,js with the require statement, you can create an Event Handler. The Event Handler defines the function that will be activated when the EventEmitter object is triggered. In this case, when the EventEmitter object is triggered, a console function is called that simply displays the statement “Function one has been activated.”

The next step is to assign the “on” method to the EmitterOne EventEmitter object. This method requires two parameters, a trigger name that is assigned to the EventEmtter (anything you like, activate is used here) and the name of the Event Handler that will trigger the function. In this case it’s myEventHandler. The “emit” method must also be assigned to the EventEmitter object, EmitterOne, as shown below.

When the EmitterOne.emit statement is processed, the corresponding EmitterOne.on statement with the “activate” parameter is located. The eventhandler in the emit method, myEventHandler, is then called. The eventhandler then triggers the console log function which then displays “Function one has been activated” on the screen. The “on” method effectively provides a connection between the “emit” method trigger and myEventHandler’s function.

An excellent video on the use of the Node.js EventEmitter is given in the tutorial, Tutorial for Beginners #8 – The Node Event Emitter.

StatisticsMatrix Poster
Statistics for Developers