Chapter 6

Using Events

IN THIS CHAPTER

Bullet Getting to know EventEmitter

Bullet Listening for events

Bullet Removing event listeners

Bullet Emitting events

“Events are not a matter of chance.”

—GAMAL ABDEL NASSER

Events are central to how asynchronous code works in Node.js, as described in these examples:

  • Streams (which I tell you about in Chapter 2 of Book 7) are objects that emit events when data is available.
  • Server objects (see Chapter 5 of Book 7) emit an event when a new request is received.
  • When an error occurs in Node.js, an error event is emitted. I tell you all about errors and how to respond to error events in Chapter 7 of Book 7.

In this chapter, I show you how to emit events and register event listeners in your own Node.js modules.

Introducing EventEmitter

Every object that emits events is an instance of the EventEmitter class. Instances of EventEmitter have an emit() method that emits an event when called. These objects also inherit an on() method that you can use to attach functions to named events.

When an event is emitted, any functions registered to that event are called synchronously. ...

Get JavaScript All-in-One For Dummies 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.