Skip to content

Instantly share code, notes, and snippets.

@aelshamy
Last active February 1, 2016 21:01
Show Gist options
  • Save aelshamy/084ec27daa8df4381573 to your computer and use it in GitHub Desktop.
Save aelshamy/084ec27daa8df4381573 to your computer and use it in GitHub Desktop.
Showcase of the observer design pattern
var Subject = function(){
var self = this;
self.observers = [];
return{
subscribeObserver:function(observer){
self.observers.push(observer);
},
unsubscriberObserver:function(observer){
var index = self.observers.indexOf(observer);
if(index > -1){
self.observers.splice(index, 1);
}
},
notifyObserver: function(observer){
var index = self.observers.indexOf(observer);
if(index > -1){
self.observers[index].notify(index+1);
}
},
notifyAllObservers: function(){
for(var i = 0; i< self.observers.length; i++){
self.observers[i].notify(i+1);
}
}
};
};
var Observer = function(){
return{
notify: function(index){
console.log("Observer" + index + " is notified!");
}
};
};
var subject = new Subject();
var observer1 = new Observer();
var observer2 = new Observer();
var observer3 = new Observer();
var observer4 = new Observer();
subject.subscribeObserver(observer1);
subject.subscribeObserver(observer2);
subject.subscribeObserver(observer3);
subject.subscribeObserver(observer4);
subject.notifyObserver(observer2);
subject.notifyAllObservers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment