Wednesday, May 25, 2011

javascript design patterns - observer

Design patterns are not OOP language specific. Javascript is a plasticine language, it can mimic OOP, so design patterns apply too.

Observer pattern is probably the most wildly used design pattern in frontend javascript programming. All those events and listeners, they are some sort of observer pattern implementation(Is there something called backend javascript programming? There is! And i believe one day it will dominate. Check http://nodejs.org if you are interested. Why do we have to use PHP at the backend and javascript at the frontend? Isn't it amazing we can use one langauge at both frontend and backend?)

Here is a very simple observer example:

function Observable() {
    this.observers = [];
}
Observable.prototype.addObserver = function(observer) {
    this.observers.push(observer);
};

Observable.prototype.notifyObservers = function() {
    for (var i=0; i<this.observers.length; i++) {
        this.observers[i].update();
    }
};

function Observer(id) {
this.id = id;
}
Observer.prototype.update = function() {
console.log(this.id + ' get updated');
}

var campaign = new Observable();
var userOne  = new Observer('one');
var userTwo  = new Observer('two');

campaign.addObserver(userOne);
campaign.addObserver(userTwo);

//console log:
//'one get updated' 
//'two get updated'
campaign.notifyObservers();

Observer is a great pattern for loose coupling. Instead of Observable object calling the Observer object's method, the Observer object is attached/added to the Observable object and gets notified. This concept is wildly used in event driven development. An event is triggered, and it is broadcasted to all the event's listeners

No comments: