jQuery Tiny Pub/Sub
Testing Pub/Sub method
HTML
<div class="red">
</div>
<div class="blue">
</div>
CSS
.red{color:red}
.blue{color:blue}
JavaScript
// jQuery Tiny Pub/Sub
(function($) {
var o = $({});
$.subscribe = function() {
o.on.apply(o, arguments);
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
}(jQuery));
// The function you pass to the .subscribe must
// return another function and you have to parse
// your arguments from an array.
function logRed() {
return function(){
$('.red').append('<br/>' + (arguments[1] || ''));
}
}
function logBlue() {
return function(){
$('.blue').append('<br/>' + (arguments[1] || ''));
}
}
// Subscribe must appear before the publish, seems
// obvious but I actually had this backwards for about
// 10mins trying to figure what I did wrong, lol.
$.subscribe('component.tc.update', logRed('foo'));
// Duplicate subscribe event does not overwrite
$.subscribe('component.tc.update', logBlue('foo'));
// Duplicate publish even does not overwrite,
// it announces each one seperately
$.publish('component.tc.update', 'namespace is component.update');
$.publish('component.tc.update', 'namespace is component.update');
// The base namspace will always trigger and this is even
// more apparent when you deeply nest them.
$.publish('component.tc', 'namespace is component');