Chapter 5

Using the Event Emitter Pattern to Simplify Event Binding

WHAT’S IN THIS CHAPTER?

  • Introducing the event emitter pattern
  • Binding and unbinding event listeners
  • Creating your own event emitter

In Node many objects emit events. For instance, a TCP server can emit a “connect” event every time a new client connects, or a file stream can emit a “data” event every time a new chunk of data is read. These objects are, in Node nomenclature, event emitters. Event emitters allow programmers to subscribe to events they are interested in. The programmer attaches a callback function that will be invoked every time a relevant event in that event emitter occurs. This publisher/subscriber pattern is very similar to the typical GUI pattern, whereby a program gets notified that a certain button was clicked. By using this pattern, a server-side program can react when, for instance, a client connects to the server, data is available on a socket, or a file gets closed.

You can also create your own event emitters. In fact, Node supplies an EventEmitter pseudo-class that can work as a base for creating your own event emitters.

UNDERSTANDING THE STANDARD CALLBACK PATTERN

Asynchronous programming does not use function return values to denote that a function is finished. Instead it uses the continuation-passing style (CPS):

Continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. (...)

A function written in continuation-passing ...

Get Professional Node.js: Building Javascript Based Scalable Software now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.