i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

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!

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.