Observer Pattern

According to the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, the definition of Observer Pattern 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.”

It is clear from the definition what an observer pattern is. Main components of an observer pattern are:

  • Subject: Maintains a list of observers, provides add, remove, or notify method.
  • Observer List: An object which keeps track of all the observers of the application.
  • Observer: Individual objects/components which wait for the notify and execute its update function.

First, we will create an object for the observer list. This object creates an array and provides normal array operations like push, pop, count, and so on.

The subject will then create and keep track of this observer list. Using this subject, we can add or remove observers in the observer list.

Each Observer will have its update function. The subject will add these observers to its observer list and, when notified it will call observer’s update function.

Let’s jump into the implementation part.

Observer List

Subject

Notice that the notify function executes the update method of all the observers it has. So an observer must have an update function. Which ideally is the purpose of writing an observer pattern.

Observer

An observer can be a simple object with an update function.

/**
 * @description a simple observer constructor with an empty update function.
 */
function Observer () {
  this.update = function () {}
}

Implementation

In the following example, we will create a checkbox UI. Along with individual selection, the UI will also have a checkbox to select all and deselect all.

The select all and deselect all functionality will be achieved using observer pattern.

All the individual checkbox element will be observers.

The main checkbox button which toggles all the checkboxes will be the subject as it will notify and execute the update function of observers.

We require an HTML layout with a button, a top-level checkbox, and a container to keep the observers.