Skip to content

Instantly share code, notes, and snippets.

@FiNGAHOLiC
Created January 16, 2012 13:41
Show Gist options
  • Select an option

  • Save FiNGAHOLiC/1620926 to your computer and use it in GitHub Desktop.

Select an option

Save FiNGAHOLiC/1620926 to your computer and use it in GitHub Desktop.
Observer Pattern
// http://shichuan.github.com/javascript-patterns/
var observer = {
addSubscriber : function(callback){
this.subscribers[this.subscribers.length] = callback;
},
removeSubscriber : function(callback){
for(var i = 0; i < this.subscribers.length; i++){
if(this.subscribers[i] === callback){
delete this.subscribers[i];
};
};
},
publish : function(){
for(var i = 0; i < this.subscribers.length; i++){
if(typeof this.subscribers[i] === 'function'){
this.subscribers[i](what);
};
};
},
make : function(o){
for(var i in this){
if(this.hasOwnProperty(i)){
o[i] = this[i];
o.subscribers = [];
};
};
}
};
var blogger = {
writeBlogPost : function(){
var content = 'Today is ' + new Date();
}
};
var la_times = {
newIssue : function(){
var paper = 'Matians have landed on Earth!';
}
};
observer.make(blogger);
observer.make(la_times);
var jack = {
read : function(what){
console.log('I just read that ' + what);
}
};
var jill = {
gossip : function(what){
console.log('You didn\'t hear it from me, but ' + what);
}
};
blogger.addSubscriber(jack.read);
blogger.addSubscriber(jill.gossip);
blogger.writeBlogPost();
blogger.removeSubscriber(jill.gossip);
blogger.writeBlogPost();
la_times.addSubscriber(jack.read);
la_times.addSubscriber(jill.gossip);
la_times.newIssue();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment