Implementing Event Emitters and Listeners
In the following chapters, you have opportunities to implement a lot of the events that are built into the various Node.js modules. This section focuses on creating your own custom events as well as implementing listener callbacks that are implemented when an event is emitted.
Adding Custom Events to Your JavaScript Objects
Events are emitted using an EventEmitter
object. This object is included in the events
module. The emit(eventName, [args])
function triggers the eventName
event and includes any arguments provided. The following code snippet shows how to implement a simple event emitter:
var events = require('events');var emitter = new events.EventEmitter();emitter.emit("simpleEvent"); ...
Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.