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)
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

