I’ve been always fascinated by the power of JavaScript. Recently I had a tour to Ruby and the event machine. I’ve got to say Ruby stands no where near the power and flexibility of JS (Gosh I am in love again). There is a list of custom event system available including ones from famous giants like jQuery, Mootools, YUI. The whole idea of having an event published, and subscribers responding to them reminds me of the small-talk (again Ruby has a good attempt but not as good as JS). Just in curiosity of custom events, I went drilling down how to do it, and the fantastic Dean Edward’s article derived me nuts! In my hunt for DOM styled event equalizer in JS I derived a trick, but later came across a PubSubJS library already doing that. But nevertheless I still beat it on size at cost of readability, and few features. So if you are curious or doing plain JS on mobile devices this is supposed to be helpful and fully customizable.
You can checkout a demo here (open debug console to see the magic)
Code is pretty minimal and fits under 404 bytes when compressed, have a taste:
PubSub = (function(){
var lst = {};
return {
// Subscribe for msg with function "fun" scoped with "obj" and additional parameters "ar"
sub: function(msg, fun, obj, ar){
lst[msg] = lst[msg] || [];
ar = ar || [];
obj = obj || window;
lst[msg].push({args: ar, me: obj, f: fun});
},
// Publish an event "msg" with event event.data = dat and que makes the call itself async (call to pub)
pub: function(msg, dat, que){
var me = arguments.callee;
if(que){
setTimeout(function(){
me.apply(me, arguments);
}, 0);
}
var curr = lst[msg] || [];
curr.filter(function(el){
try{
el.f.apply(el.me, [].concat({data: dat}, el.args));
}catch(e){
setTimeout(function(){throw e;}, 0);
}
return true;
});
},
// Un-subscribe "fun" from event "msg"
unsub: function(msg, fun){
var cur = lst[msg] || [];
lst[msg] = cur.filter(function(el){
return el.f !== fun;
});
}
}
})();
Design by Simon Fletcher. Powered by Tumblr.
© Copyright 2010