Skip to content

Instantly share code, notes, and snippets.

@vladkotu
Forked from cowboy/HEY-YOU.md
Created October 31, 2011 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladkotu/1327219 to your computer and use it in GitHub Desktop.
Save vladkotu/1327219 to your computer and use it in GitHub Desktop.
jQuery Tiny Pub/Sub: A really, really, REALLY tiny pub/sub implementation for jQuery.
/* jQuery Tiny Pub/Sub - v0.7 - 10/27/2011
* http://benalman.com/
* Copyright (c) 2011 "Cowboy" Ben Alman; Licensed MIT, GPL */
(function($) {
var o = $({});
$.subscribe = function() {
o.on.apply(o, arguments);
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
$.multiarmed = function (a){
var events = a.events,
callback = a.callback,
stored = {},
fired = 0,
slice = Array.prototype.slice;
return function (e){
var idxE = $.inArray(e.type, events),
type = e.type;
if ( -1 === idxE ) return true;
stored[type] = slice.call(arguments, 1);
delete events[idxE];
fired += 1;
if (fired === events.length){
callback.call(a.context || {}, stored);
}
};
};
}(jQuery));
@vladkotu
Copy link
Author

var multiarmedHandler = $.multiarmed({
    events   : ['event:one', 'event:two'],
    callback : function (){
        console.info('all events are fired', arguments)
        console.info('this.is context',this)
    },
    context  : {optionsl:'onject'} 
});

$.subscribe('event:one', multiarmedHandler );
$.subscribe('event:two', multiarmedHandler );

$.publish('event:one', 1,2,3);
$.publish('event:two', 4,5,6);

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