Last active
December 29, 2015 14:29
-
-
Save kkemple/7684559 to your computer and use it in GitHub Desktop.
quick pub/sub with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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