with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

JavaScript Publisher

Friday, November 10th, 2006

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!

20 Responses to “JavaScript Publisher”

  1. Binny V A

    Loved the ‘hilariously humorous (yet highly educational)’ illustration. Trying to make up for yesterday’s illustration, right? ;-)

  2. Dustin Diaz

    @Binny: Ok, so maybe I might be the only one laughing. But hopefully it proves a point and you’ve gained extra understanding of the concept :) I wasn’t making up for anything; I just felt a bit more inclined to do something goofy.

  3. kentaromiura

    Now it’s Perfect, I finally can deliver the sfChronicles to my Best Subscriber: Blanka

    ^_^;;

  4. Bramus!

    Must say that I like this concept more than yesterday’s post: Love the fact that each Publisher holds its own subscribers array.

    Very neat code, and wicked demo!

    Thanks,
    Bram.

  5. Carlton

    That demo opens up a can of whoop ass on any other javascript demo I have ever seen…helps explain the concept really nice too!
    Out of curiousity are the characters ordered in preference order? I know these would be my choice!

  6. Jim

    Wow. Absolutely brilliant demo page. And a great bit of code. Will you marry me? Oh…we’re both married…and my proposal is not legal in most states. Oh well.

  7. Nathan Smith

    Nice article. I just wanted to say that anyone who uses Street Fighter II characters in code demos truly is an uber-geek.

  8. Dustin Diaz

    @Christian: I used to think I was a good Blanka player, but anyone who knows what they’re doing with him can seriously do some good butt whoopin’. I knew you’d appreciate this version better :)

    @Bramus: I think both concepts have their place. As shown in yesterdays post, adding the ability to subscribe to an event based off an object is very useful. It allows you to bind the event with whom is responsible for it. Eg:

    myAnimation.onComplete.subscribe(
        function() {
            // do stuff here
        }
    );

    Nonetheless, I have already shown a great use for this model as well. It delights me that you thought it was wicked!

    @Carlton: Making demonstrations of my code is something I would consider a “best practice” for any Programmer who is trying to explain complicated code. And in other ways it’s more like a requirement just to explain a concept.

    Another benefit to illustrating code through demonstrations is that I’m effectively communicating a pattern - even if you don’t know JavaScript. The fact that it’s a “programming pattern” theoretically means it can be applied to several other languages.

    Oh, and yes; the characters are definitely in the order of my preference. I’ve also chosen Ken over Ryu as well because his helicopter kick is faster.

    @Jim: As a direct quote (yet slightly altered) from Adam Sandlers 50 first dates, “Somehow I just prefer taco over sausage.” Thanks for the kind comment though :p

    @Nathan: That’s the only way I can effectively keep my readers. Otherwise some of these topics can make for a dull and boring blog.

  9. Peter Goodman

    So, this is just the observer and dispatcher patterns being used together? Although not JS, you might be interested in http://www.flyingwithfire.com/2006/08/24/observers-and-dispatchers/

  10. Dustin Diaz

    @Peter: Yes. The subscribers are the observers. The publisher delivers (or dispatches).

  11. milo

    Cool demo and a pretty good article, Dustin, playing Street Fighter now.

  12. Jack Slocum

    You can delete my comment on the other post as this more accurately portrays the Observer pattern. (I read them in the wrong order)

  13. kentaromiura

    Btw my correct name is Cristian, not Christian ;)

  14. lordmarin

    HEllo,
    can you write a tutorial for javascript image manipolation? resize, and more?
    Thx
    lordmarin

  15. Nate Cavanaugh

    Heya Dustin,
    I understand that you wrote this a while ago, but I am just now getting around to playing with it.

    While it’s quite cool, I am running into an issue with the subscribe method. The only code I have is the Sugar Arrays, the Publisher.js the code copy/pasted from the demo (minus the YUI specific stuff).

    Basically, the bug I am running into is that the .some method isn’t working properly, or at least the filtering mechanism is busted.

    The problem, in the short of it, is that I can subscribe the Recipient multiple times, and they receive a delivery for every time they’ve been subscribed.

    I know the some method is looking to see if the current Recipient is already in the subscribers array, but it is always returning false.

    Any thoughts as to what could be going on?

    Thanks!

  16. Abdul Majeedh

    Hi Everybody,

    Could any one help me with the code for adding the elements from drop down list into the fieldset i.e., text area upon hitting the add button.

    Thanks and Regards,

    abdul

  17. SEO

    The demo doesn’t appear to be working in IE7

    Is there anything changed with the way Explorer 7 handles the code, or anything i can do to modify the code to work?

    Thanks.

  18. Anonymous

    Dojo has gud support for publish subscribe pattern.
    Its very easy to publish and listen to events wid dojo.
    Dojo has other gr8 features like I.O and widgets

    http://www.jyog.com

  19. Andres Vasilev

    demo doesn’t appear to be working in IE7

  20. Dui

    I don’t see the demo. Is this still working Dustin?

    Found this page on G. Gonna poke around a bit. Lord knows I need the help!!!

    :O)

Leave a Reply

Phone Number:

If you're about to post code in your comment, please wrap your code with the tag-combo <pre><code>. Also please escape your html entities - otherwise they will be stripped out. I recommend using postable.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Flickr

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.