i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

JavaScript Observer Class

First off, let me be the 763rd person to say that JavaScript does not have have a formal class system, however it does have the expressive nature to represent the notion of a class. That being out of the way, this entry is about representing the Observer Pattern in JavaScript; otherwise known as the publisher/subscriber model. As some already might know, it is already well demonstrated in modern event handling BOM's such as IE's attachEvent or W3's addEventListener which allow you to register multiple listeners, and notify each callback by firing one event.

You might also know that some JavaScript libraries such as Dojo, YUI, and Prototype have implemented generic utilities that easily allow you to set up your publishers and allow client code to subscribe to these events....

Well, here's mine. It's basic and to the point, and only uses a wee bit of code.

Observer Class

function Observer() {

    this.fns = [];

}

Observer.prototype = {

    subscribe : function(fn) {

        this.fns.push(fn);

    },

    unsubscribe : function(fn) {

        this.fns = this.fns.filter(

            function(el) {

                if ( el !== fn ) {

                    return el;

                }

            }

        );

    },

    fire : function(o, thisObj) {

        var scope = thisObj || window;

        this.fns.forEach(

            function(el) {

                el.call(scope, o);

            }

        );

    }

};
Take special note that a few of the extra array methods (filter and forEach) need to be added to supplement browsers that do not support them. You could just simply grab the two from here, or just grab them all from my minified collection.

Implementation

This part is easy.

subscribing and publishing

/* 

    * Publishers are in charge of "publishing" eg: Creating the Event

    * They're also in charge of "notifying" (firing the event)

*/

var o = new Observer;

o.fire('here is my data');





/* 

    * Subscribers basically... "subscribe" (or listen)

    * And once they've been "notified" their callback functions are invoked

*/

var fn = function() {

    // my callback stuff

};

o.subscribe(fn);



/*

    * Don't want to subscribe anymore?

*/

o.unsubscribe(fn);

Go ahead and have a play around. See it live in action (albeit a dull and boring illustration)

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.