Created
January 16, 2012 13:41
-
-
Save FiNGAHOLiC/1620926 to your computer and use it in GitHub Desktop.
Observer Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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