A Pen by Andrew Kirchmyer on CodePen.
Created
November 17, 2013 03:57
-
-
Save akirchmyer/7508911 to your computer and use it in GitHub Desktop.
A Pen by Andrew Kirchmyer.
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
| var publisher = { | |
| subscribers: { | |
| any: [] | |
| }, | |
| subscribe: function(fn, type) { | |
| type = type || 'any'; | |
| if (typeof this.subscribers[type] === 'undefined') { | |
| this.subscribers[type] = []; | |
| } | |
| this.subscribers[type].push(fn); | |
| }, | |
| unsubscribe: function(fn, type) { | |
| this.visitSubscribers('unsubscribe', fn, types); | |
| }, | |
| publish: function(publication, type) { | |
| this.visitSubscribers('publish', publication, type); | |
| }, | |
| visitSubscribers: function(action, arg, type) { | |
| var pubtype = type || 'any', | |
| subscribers = this.subscribers[pubtype], | |
| i, | |
| max = subscribers.length; | |
| for (i = 0; i < max; i += 1) { | |
| if (action === 'publish') { | |
| subscribers[i](arg); | |
| } | |
| else { | |
| if (subscribers[i] === arg) { | |
| subscribers.splice(i, 1); | |
| } | |
| } | |
| } //for | |
| } //publisher.visitSubscribers | |
| }; // publisher | |
| function makePublisher(o) { | |
| var i; | |
| for (i in publisher) { | |
| if (publisher.hasOwnProperty(i) && typeof publisher[i] === 'function') { | |
| o[i] = publisher[i]; | |
| } | |
| } | |
| o.subscribers = {any: []}; | |
| } | |
| // Create a new publisher | |
| var paper = { | |
| daily: function() { | |
| this.publish('big news today'); | |
| }, | |
| monthly: function() { | |
| this.publish("interesting analysis", "monthly"); | |
| } | |
| } | |
| makePublisher(paper); | |
| // create a subscriber | |
| var joe = { | |
| drinkCoffee: function(paper) { | |
| console.log('Just read ' + paper); | |
| }, | |
| sundayPreNap: function(monthly) { | |
| console.log('About to fall asleep reading ' + monthly) | |
| } | |
| }; | |
| paper.subscribe(joe.drinkCoffee); | |
| paper.subscribe(joe.sundayPreNap, 'monthly'); | |
| // fire some events from the publisher | |
| paper.daily(); | |
| paper.daily(); | |
| paper.daily(); | |
| paper.monthly(); | |
| // joe can become a publisher too | |
| makePublisher(joe); | |
| joe.tweet = function(msg) { | |
| this.publish(msg); | |
| } | |
| // and paper can be a subscriber of joe | |
| paper.readTweets = function(tweet) { | |
| alert('call a big meeting! Someone ' + tweet); | |
| }; | |
| joe.subscribe(paper.readTweets); | |
| // fire an event from the new publisher, joe | |
| joe.tweet('hated the paper today'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment