HTML5 Zone is brought to you in partnership with:

My name is Sagar Ganatra and I'm from Bangalore, India. I'm currently employed with Adobe India and I work there as a ColdFusion Engineer. At Adobe, I have worked on various features of ColdFusion and ColdFusion Builder. I'm very much passionate of web technologies and have a very good understanding of jQuery, Flex, HTML5, Java and of course ColdFusion. Sagar H is a DZone MVB and is not an employee of DZone and has posted 41 posts at DZone. You can read more from them at their website. View Full User Profile

Pushing Ajax Responses using Observer Pattern in JavaScript

09.27.2012
| 17313 views |
  • submit to reddit
Last week I'd played around with couple of design patterns in JavaScript (Constructor and Module pattern). I really liked the Module pattern i.e. the approach taken in JavaScript to enable encapsulation of data in a Class (functions in JavaScript). I was building an application using these Design patterns but found that making Ajax request inside a function in a module was not the right approach. JavaScript would send a request and start executing the next statement. I wanted to use an approach that would push the data from the Model whenever there was some new data available. This lead me to try the 'Observer pattern' in JavaScript.

After reading a bit on the Observer pattern, I realized that it's used in almost all client side JavaScript programs in the form of event handlers. All browser events are examples of this pattern i.e. whenever an event takes place, the registered event handler is fired. Here, you want a particular function to be executed whenever there is a change in the state of another object. The function can be viewed as an Observer which performs the necessary action when the state of another object - let's call it the 'Subject' changes. The 'Subject' is responsible for notifying the Observers of the change in state and pass the necessary data to it's Observers. To do this the Subject has to maintain a list of Observers who are interested in getting notifications.

In my application, I was trying to fetch tweets by sending an Ajax request to Twitter server. Once the tweets are available, I wanted all my observers to be notified with the recent tweets. Here, my Subject is 'Twitter' which is responsible for fetching the tweets and notifying all its observers whenever the data is available. Also, it is responsible for maintaining a list of observers who are interested in receiving notifications. The way I modeled this application is to define a generic class 'Subject' and a class 'Twitter' which would extend the Subject class.
/*
* Define a generic class Subject with two methods
* 'addObserver' and 'notifyObserver'
*/
function Subject() {
this.observerList = [];
}

Subject.prototype.addObserver = function(observerObj) {
this.observerList.push(observerObj)
}

Subject.prototype.notifyObserver = function(msg) {
for (var i = 0, length = this.observerList.length; i < length; i++) {
this.observerList[i]['updateFn'](msg);
}
}
Here the Subject class defines an array 'observerList' and two methods 'addObserver' and 'notifyObserver'. The addObserver method would add the observer object to the array and notifyObserver would iterate through the list of observers and send notifications whenever there is a new message. Now the Twitter class can extend the Subject class:
/*
* Define a Twitter class which extends the Subject class
*/
function Twitter(handlerName,observerObj) {
//Call the parent class - Subject
Subject.call(this);

//Handler name is the username for which tweets has to be retrieved
this.handlerName = handlerName;

//add the observer object
this.addObserver(observerObj);

//fetch the status messages
this.init();	
}

Twitter.prototype = Object.create(Subject.prototype);

//Define the init method that will fetch the status messages
Twitter.prototype.init = function() {
parent = this;
$.ajax({
url: 'http://twitter.com/statuses/user_timeline/' + parent.handlerName + '.json?callback=?',
success: function(data) {
//iterate over the list of tweets
$.each(data,function(index,value)
{
var message = value.text;

//ignore the reply messages i.e. messages that start with '@'
  if(message[0] != '@')
  {
  //Check whether the status message contains a link
  if((index=message.indexOf('http://')) > 0)
  {
  substr1 = message.substr(index);
  nextIndex = substr1.indexOf(' ');
  substr2 = (nextIndex > 0)? substr1.substr(0,substr1.indexOf(' ')):substr1.substr(0);
  pos1 = message.indexOf(substr2);
  pos2 = pos1 + substr2.length;
  newMessage = [message.slice(0,pos1),'<a href='+ substr2+ ' target="_blank" >' + substr2 + '</a>',message.slice(pos2)].join('');

  //notify the Observer of the new message
  parent.notifyObserver(newMessage);
  }
  else {
  parent.notifyObserver(message);
  }	
  }
});
},

//if there is an error, throw an Error message
error: function(data) {
parent.notifyObserver("Error");
},

dataType: 'json'
});
}
The constructor of Twitter class would call the parent constructor and then add the observer object (by invoking addObserver) to the list. Now it's ready to fetch the tweets for the provided handlerName. The init function then sends an Ajax request to fetch the tweets and once the data is received it would call the notifyObserver function. Note that the notifyObserver function is defined in the Subject class. The implementation of the Observer is pretty simple:
//Define an Observer class
function Observer(name, updateFn) {
this.name = name;
this.updateFn = updateFn;
}

//Create an instance of Observer class
observerObj = new Observer("observer1", function(msg) {	console.log(msg); });

//Create an instance of the Subject and provide the observer object
tObject = new Twitter("sagarganatra",observerObj);

The Observer needs to provide the function (or the handler) that should be called when the Subject has a new message. In this case the updateFn would log the messages that it receives from the Subject.

 

 

Published at DZone with permission of Sagar H Ganatra, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)