concept EventEmitter in category javascript

appears as: EventEmitter, n EventEmitter
Node.js in Practice

This is an excerpt from Manning's book Node.js in Practice.

Sooner or later every Node developer runs into EventEmitter. At first it seems like something only library authors would need to use, but it’s actually the basis for most of Node’s core modules. The streams, networking, and file system APIs derive from it.

You can inherit from EventEmitter to make your own event-based APIs. Let’s say you’re working on a PayPal payment-processing module. You could make it event-based, so instances of Payment objects emit events like paid and refund. By designing the class this way, you decouple it from your application logic, so you can reuse it in more than one project.

We have a whole chapter dedicated to events: see chapter 4 for more. Another interesting part of EventEmitter is that it’s used as the basis for the stream module.

Although EventEmitter is an integral part of Node’s standard library, and an elegant solution to many problems, it can be the source of a lot of bugs in larger projects where people may forget the name of a given event. One way around this is to avoid writing events as strings. Instead, an object can be used with properties that refer to the event name strings.

To use EventEmitter, the base class must be inherited from. This section includes techniques for inheriting from EventEmitter and mixing it into other classes that already inherit from another base class.

The canonical example of using events in Node is inheriting from EventEmitter. This can be done by using a simple prototype class—just remember to call EventEmitter’s constructor from within your new constructor.

The first listing shows how to inherit from EventEmitter.

Listing 4.1. Inheriting from EventEmitter