g-akshay
2/21/2017 - 5:55 PM

Observer Pattern

Observer Pattern

function Subject(){
  this.observers = new ObserverList();
}
 
Subject.prototype.addObserver = function( observer ){
  this.observers.add( observer );
};
 
Subject.prototype.removeObserver = function( observer ){
  this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};
 
Subject.prototype.notify = function( context ){
  var observerCount = this.observers.count();
  for(var i=0; i < observerCount; i++){
    this.observers.get(i).update( context );   // update method is implemented in all the observer
  }
};
function ObserverList(){
  this.observerList = [];
}

ObserverList.prototype.count = function(){
  return this.observerList.length;
};
 
ObserverList.prototype.add = function( obj ){
  return this.observerList.push( obj );
};
 
ObserverList.prototype.get = function( index ){
  if( index > -1 && index < this.observerList.length ){
    return this.observerList[ index ];
  }
};
 
ObserverList.prototype.indexOf = function( obj, startIndex ){
  var i = startIndex;
 
  while( i < this.observerList.length ){
    if( this.observerList[i] === obj ){
      return i;
    }
    i++;
  }
 
  return -1;
};
 
ObserverList.prototype.removeAt = function( index ){
  this.observerList.splice( index, 1 );
};
  • An object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state
  • Subject: maintains a list of observers, facilitates adding or removing observers
  • Observer: provides a update interface for objects that need to be notified of a Subject's changes of state

pros

  • helps maintain consistency between related objects without making classes tightly coupled

cons

  • subject has no track of when the observer finishes its task
  • An observer is unware of other observers

blog

// skeleton

function Observer(){
  this.update = function(){
    // ...
  };
}

// every observer must have an update method, so that it can do things once notified