Node.js – Handling Events

Node.js – Handling EventsNode.js – Handling Events

In this section, I discuss dealing with Node events. A lot of settings exist experimental activities allow for the scheduling and recording of actions though events triggered and listened to. You will learn about the methods that Node allows you used for dealing with events should fit most of your event request addressing needs.

I am also discussing the use of time and scheduling to regulate the duration and when certain by-laws must be implemented in an application Node. Can you think of a dozen situations in which this might work. Like all normal things JavaScript actions at Node, times and job classifications are international jobs, and as such, the use of required () jobs to introduce them is not appropriate. These methods discussed in the section both can be asynchronous and synchronous functions.

Using Event Emitters

In Node, to generate an event, just import the events module and use the Event Emitter object’s emit() method. The example below shows creating a simple event using the emit method:

var events = require("events");
var emitter = new events.EventEmitter();
emitter.emit("myEvent");

You may also pass in extra arguments that will bind to the event, such as adding a new record to a database. A easy example of adding an Author and book Title appears below:

var events = require("events");
var emitter = new events.EventEmitter();
var author = "Slim Shady";
var title = "The real Slim Shady";
// add record to db
emitter.emit("addAuthorTitle", author, title);

Using event.addListener and event.on

Events are worthless unless there is some action to execute in response to an event. To handle an event reaction, Node provides the on() and addListener() technique. Both of these technique take an event name and handler function as arguments. These technique can be used interchangeably as both do the same thing, and that is to perform code based on events. Continuing with the Author and Title example, but attaching a handler function to be invoked once the event is triggered (created in this case):

var events = require("events");
var emitter = new events.EventEmitter();
var author = "Slim Shady";
var title = "The real Slim Shady";
//an event listener
emitter.on("addAuthorTitle", function(author, title) {
console.log("Added Author and Title " + author + " - " + title); });
//add record to db
// then emit an event
emitter.emit("addAuthorTitle", author, title);

An important thing to note is that the event listener should be set up before the emitting of the event. Doing it the other way around will not work and the event will not be handled by the handler function.

Using once

There may be times where you only want your application to respond to an event (or type of event) one time (i.e. the first time the event occurs). To do this, Node provides the once() method. The once method is used just like the addListener and on methods, but only allows for responding to the event one time. An example appears below:

var events = require("events");
var emitter = new events.EventEmitter();
var author = "Slim Shady";
var title = "The real Slim Shady";
//an event listener
emitter.once("addAuthorTitle", function(author, title) {
console.log("Added Author and Title " + author + " - " + title); });
//add record to db
// then emit an event
emitter.emit("addAuthorTitle", author, title);
emitter.emit("addAuthorTitle", author, title);

Notice the event to add Author records is emitted twice, but running this code will yield only one handling of the event because the once technique was used. Now that you have a good comprehending of event handling, it is time to move on to time-based functions for arranging when callback functions are executed.

Using setTimout

The setTimeout method is useful for executing a callback function that needs to be executed sometime in the future. The parameters for this performance are the callback function to be performed and the time elapsed before it should be executed (in millisecs). Following the time parameter are one or more arguments passed to the callback function. An easy example of using the setTimout method appears below:

setTimeout(function(str1, str2) {
console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");

Two strings are passed in and then written down to the console after a second of waiting before executing the method. There also may be instances where you need to cancel the time out before the execution of the callback function. The setTImout method comes back an identifier that can be used with the clearTimeOut method. A simple example of using the clearTimeout method appears below:

var timeOut = setTimeout(function(str1, str2) {
console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");
clearTimeout(timeOut);

The example overhead cancel’s the function call immediately though in real-world scenarios the cancellation will occur based on an event. Using setInterval What if you require to repeat the execution of your code block at specified intervals? For this, Node has a method called setInterval() and clearInterval().

The setInterval function is very lots like the setTimeout, event using the same parameters like as the callback function, delay and any optional arguments for passing to the callback function. A simple example of setInterval appears below:

var interval = setInterval(function(str1, str2) {
console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");
clearInterval(interval);