Skip to content

Instantly share code, notes, and snippets.

@kkemple
Last active December 29, 2015 14:29
Show Gist options
  • Save kkemple/7684559 to your computer and use it in GitHub Desktop.
Save kkemple/7684559 to your computer and use it in GitHub Desktop.
quick pub/sub with jQuery
/**
* Create an observer pattern for jQuery
* allows you to alias trigger with publish,
* on with subscribe,
* and off with unsubcsribe
* Useful for custom events
*
*USAGE:
* $(el).subscribe('customEvent', function() {
* do something when customEvent is published
*
* No longer need to subscribe to custom event
* $(el).unsubscribe('customEvent');
* });
*
* Custom event is fired
* $.publish('customEvent');
*/
(function($) {
var o = $({});
$.each({
trigger: 'publish',
on: 'subscribe',
off: 'unsubscribe'
}, function(key, val){
jQuery[val] = function() {
o[key].apply(o, arguments);
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment