Javascript – Observer Pattern pour vos onglets
Bon, nous allons voir comment appliquer un « Observer Pattern » (patron Observateur) en javascript.
Tout d’abord, nous avons besoin de 2 types d’objets :
- Un Objet qui observe possédant une méthode update :
Observer = function(name) {
this.name = name;
this.update = function(observable) {
if (observable.nav == this.name) {
this.className = 'nav_selected';
show.call($(this.name+'s'));
} else {
this.className = 'nav';
hide.call($(this.name+'s'));
}
}
};
- Un Objet observé possédant un attribut qui référence les objets qui observent et 2 méthodes
Observable = function() {
this.observers = new Array();
this.notifyObservers = function() {
for (var i=0; i < this.observers.length; i++) {
this.observers[i].update(this);
}
}
this.addObserver = function(observer) {
this.observers.push(observer);
observer.update(this);
}
};
Et voilà (ou presque), on crée un objet mod Nav qui héritera par la suite d’Observable :
var modNav = {
nav:'client',
all:['client','product','group','schedule']
};
modNav.setNav = function(o) {
this.nav = (typeof(o) == 'string') ? o : o.id ;
this.notifyObservers();
}
modNav.getNav = function() {
return this.nav
}
modNav.init = function() {
for (var j=0; j
var m = this.all[j];
Observer.call($(m),m);
this.addObserver($(m));
}
}
Il ne reste plus qu’à faire hériter les objets div modifiable (un onglet <=> une div) :
Observable.call(modNav);
modNav.init();
Avec, pour notre exemple :
Et voilà (enfin) les onglets sont observables et nos moutons sont bien g…

