- Using Event Emitters
- Using event.addListener and event.on
- Using once()
- Using setTimeout()
- Using setInterval()
- Using setImmediate()
- Partitioning Long-running Tasks
- Conclusion
Using event.addListener and event.on
Events are worthless unless there is some action to perform in response to an event. To handle an event response, Node provides the on() and addListener() methods.
Both methods take an event name and handler function as arguments. These methods can be used interchangeably because they do the same thing: execute code based on events.
Continuing with the author and title example, but adding a handler function to be invoked once the event is triggered (created in this case), you see the following:
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);
Note that the event listener must be set up before the emitting of the event. Doing it the other way around does not work, and the event will not be handled by the handler function.