Using once()
Sometimes you want your application to respond to an event (or type of event) only one time (i.e., the first time the event occurs). To do this, Node provides the once() method. It is used just like the addListener() and on() methods, but allows for responding to the event only once. An example appears here:
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 that the event to add author records is emitted twice, but running this code yields only one handling of the event because the once() method was used.
Now that you have a good understanding of event handling, it is time to move on to time-based functions for managing when callback functions are executed.