Skip to content

Instantly share code, notes, and snippets.

@obenjiro
Created October 13, 2012 22:26
Show Gist options
  • Save obenjiro/3886422 to your computer and use it in GitHub Desktop.
Save obenjiro/3886422 to your computer and use it in GitHub Desktop.
Smallest Pub\Sub Pattern (268 chars)
//pubsub pattern
(function (eventList, i, item) {
eventList = [];
this.pubsub = {
fire: function (event, a, b, c, d, e) {
for (i in eventList) {
if (eventList[i] == event) {
eventList[+i + 1](a, b, c, d, e);
}
}
},
subscribe: function (event, fn) {
eventList.push(event, fn);
},
unsubscribe: function (fn) {
eventList.splice(eventList.indexOf(fn) - 1, 2);
},
unsubscribe_all: function (event) {
for (i = 0; item = eventList[i]; i++) {
if (item == event) {
eventList.splice(i, 2);
i--;
}
}
}
}
})();
//pubsub pattern - obfuscated (268 chars)
!function(a,b,c){a=[],this.pubsub={fire:function(c,d,e,f,g,h){for(b in a)a[b]==c&&a[+b+1](d,e,f,g,h)},subscribe:function(b,c){a.push(b,c)},unsubscribe:function(b){a.splice(a.indexOf(b)-1,2)},unsubscribe_all:function(d){for(b=0;c=a[b];b++)c==d&&(a.splice(b,2),b--)}}}()
//pubsub usage
var handler = function() {
console.log("handler function is called");
}
pubsub.subscribe("/inbox/update", handler);
pubsub.subscribe("/inbox/message", function(){
console.log("/inbox/message fired - arguments - " + JSON.stringify(arguments));
});
pubsub.fire("/inbox/update");
pubsub.fire("/inbox/message");
pubsub.fire("/inbox/message", 1, 2);
pubsub.unsubscribe_all("/inbox/message");
pubsub.unsubscribe(handler);
pubsub.fire("/inbox/message");
pubsub.fire("/inbox/update");
@FarSeeing
Copy link

Save some bytes:

subscribe: eventList.push,

Any number of arguments pass to fire function:

fire: function(event){
    for(i=0;item=eventList[i];i++){
        if (item == event) {
            eventList[i+1]([].shift.call(arguments,1));
        }
    }
},

@obenjiro
Copy link
Author

Wow :) awesome tnx!

@obenjiro
Copy link
Author

  1. this one
    subscribe: eventList.push,

can only work if i use 'bind' - otherwise i just pointing to 'push' function and 'eventList' is just forgoten
subscribe: eventList.push.bind(eventList),

the problem is that 'bind' function isn't supported on IE8, so this is not option for me

  1. this one
        fire: function(event,a,b,c,d,e){
            for(i = 0; item = eventList[i]; i++){
                if (item == event) {
                    eventList[i+1](a,b,c,d,e);
                }
            }
        },

is also can be called with variable argumets lenght (but up to 5), and more over it's 7 chars shorter when minified

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment