JavaScript Publisher
As a revisit to my previous post about making an Observer Class in JavaScript, I went ahead and built something new. You can call it "Observer Reloaded," but I'm calling it "Publisher." It holds a more truthful meaning to the original publish/subscribe model of the Observer Pattern.
In other words, actions respond upon their hosts notifying them. It is in fact, more or less of a perspective change. Rather than thinking "what object do I want to listen for," it's "who is watching me, and when should I tell them something."
Here's how it works
It's simple. You're a publisher... let's say, a Newspaper publisher. You've got other buddies too in the newspaper industry. Great. Let's set 'em up.
Setting up your publisher Objects
/*
* Newspaper Vendors
*/
var NewYorkTimes = new Publisher;
var AustinHerald = new Publisher;
var SfChronicle = new Publisher;
Ok, now you're hoping that along comes some people that want to subscribe your paper. After all, that's how you stay in business, right?
These are just ordinary people
/*
* People who like to read
* (Subscribers)
*/
var Ken = function(from) {
console.log('Delivery from '+from+' to Ken');
};
var ChunLi = function(from) {
console.log('Delivery from '+from+' to Chun Li');
};
var Ryu = function(from) {
console.log('Delivery from '+from+' to Ryu');
};
Notice our avid news readers are all ready to receive some data from whomever decides to deliver. Now, the next step is to subscribe to newspapers. Easy enough!
Subscribing to Publishers
/*
* Let them subscribe to newspapers!
*/
Ken.
subscribe(NewYorkTimes).
subscribe(SfChronicle);
ChunLi.
subscribe(AustinHerald).
subscribe(SfChronicle).
subscribe(NewYorkTimes);
Ryu.
subscribe(AustinHerald).
subscribe(SfChronicle);
Time for a Delivery
People need their news. Simple enough. "Deliver" your product.deliver method
NewYorkTimes.deliver('Here is your paper! Direct from the Big apple');
Demonstration and downloads
Want this kind of functionality in your toolkit? Feel free to download the extremely lightweight JavaScript Publisher (1.65k), or the minified version (0.77k). Also, please be sure to take a look at the hilariously humorous (yet highly educational) illustration that I've put together for your convenience. Enjoy!
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

