Tuesday, February 7, 2012

basic diy pubsub

So to solve a problem at work I wrote a basic pubsub, a publish/subscribe model so parts of our page can notify other parts of events they care about... it's a powerful design pattern for decoupling various components on a page. There are other implementations we coulda used, but it's pretty fun and easy to roll our own, I think the resulting code is small and robust:
var localDataBreaker = new function(){
this.callbacks = {};
this.subscribe = function(event,id,funk){
if(this.callbacks[event] == undefined){
this.callbacks[event] = {};
this.callbacks[event][id] = funk;

this.unsubscribe = function(event,id){
if(this.callbacks[event] != undefined){

this.publish = function(event,args){
if(this.callbacks[event] != undefined){
for(key in this.callbacks[event]){
var funk = this.callbacks[event][key];


(I like the idea of functions subscribing with a string key for later unsubscriptions, that seemed safer than assuming there will be a reference to the same function handy when a function wants to stop listening.)

So here's a basic test of it... we subscribe to event "foo" with an anonymous function that we key with "bar", we practice firing "foo", then we also subscribe with an event tagged "baz", we see both fire when the event occurs, then we remove "bar" and see just "baz" fire when we fire the event a third time.

localDataBreaker.publish("foo",'event  1 after just bar ');
localDataBreaker.publish("foo",'event 2 after bar and baz ');
localDataBreaker.publish("foo",'event 3 after bar removed ');

No comments:

Post a Comment