Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

The Observer Pattern

The Observer is a design pattern in which an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state (Figure 9-3).

Observer pattern

Figure 9-3. Observer pattern

When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers (which can include specific data related to the topic of the notification).

When we no longer wish for a particular observer to be notified of changes by the subject it is registered with, the subject can remove it from the list of observers.

It’s often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time. The definition of the Observer pattern provided in the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, is:

One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject’s state, they can simply detach themselves.

We can now expand on what we’ve learned to implement the Observer pattern with the following components:

Subject ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page