Handling Events in Node.js
In this article, I discuss handling events in Node.js. Most frameworks have an event-driven model that enables event setting and capturing through event triggers and listeners. You will learn about the methods that Node.js allows you to use for event handling that should fit most of your application’s event-handling needs.
I also discuss using timers and scheduling functions to control how long and when certain code should be executed in a Node application. You can probably think of a dozen situations where this would be useful.
Like all common JavaScript functions in Node, the timing and scheduling functions are global functions, so the use of the require() function to import them is not necessary.
The methods discussed in this article can be used with both asynchronous and synchronous functions.
Using Event Emitters
To create an event in Node, import the events module and use the EventEmitter object’s emit() method. The example below shows a simple event created with the emit() method:
var events = require("events"); var emitter = new events.EventEmitter(); emitter.emit("myEvent");
You can also pass in extra arguments that will bind to the event, such as adding a new record to a database. Here is a simple example of adding an author and book title:
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);