This pattern also referred as publisher – subscriber pattern describes a method to allow one object to be aware of another object changes.

It allows you to ask to be notified when the state of the observed object changes, so that you can react on that information.

As you can imagine, this pattern is widely used to implement event systems.

Have you ever write Ajax code or used a call back function?

Then you have used this pattern.

In the typical implementation the object that changes keeps a list of registered observers, when the change happens it notifies the registered objects usually by calling a function of the observer object, that function usually is called cal back function At its simplest form this pattern can be implemented this way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var publisherClass = function(){
    var subscribers=[];
    return{
        subscribe : function(callback){
            subscribers.push(callback);
        },
        publish : function(){
            for (var n = 0; n < subscribers.length; n++){
                subscribers[n].call(this, n);
            }
        }
    };
};
var subscriber = function(parameterFromPublisher){
    console.log("publisher published the following value " + parameterFromPublisher);
};
var publisher = new publisherClass();
publisher.subscribe(subscriber);
publisher.subscribe(subscriber);
publisher.publish();
//output:
// publisher published the following value 0
// publisher published the following value 1

This code works by storing an internal references to all the callbacks, when the publish() method is triggered we iterate through all of those references and execute them