I’ve decided to try out the Publish/Subscribe pattern for some of the new things we’re creating at work. So far I think it’s working out really well. The neatest thing is that a Pub/Sub system can be created in JavaScript in very little amount of code. And with the help of jQuery, you can shorten the amount of code even more.
Here is the entire system in jQuery.
jQuery.subscribe = function(signal, scope, fnName) {
var curryArgs = Array.prototype.slice.call(arguments, 3);
$(window).bind(signal, function () {
var normalizedArgs = Array.prototype.slice.call(arguments, 1);
scope[fnName].apply(signal, curryArgs.concat(normalizedArgs));
});
return jQuery;
};
jQuery.publish = function(signal) {
$(window).trigger(signal, Array.prototype.slice.call(arguments, 1));
return jQuery;
};
Notice that the subscriber function allows for partial applicationof the handler function. This can be useful in some cases.