Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Forked from rwaldron/jquery.ba-tinypubsub.js
Last active September 30, 2015 06:22
Show Gist options
  • Save softwarespot/bbcb6f0fd722082f6ebe to your computer and use it in GitHub Desktop.
Save softwarespot/bbcb6f0fd722082f6ebe to your computer and use it in GitHub Desktop.
PubSub module in jQuery
/*
* jQuery Tiny Pub/Sub - v0.1 - 2015/08/07
* http://benalman.com/
*
* Original Copyright (c) 2010 'Cowboy' Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* Made awesome by Rick Waldron, with additional ideas by Jeffrey Way and softwarespot
* URL: https://gist.github.com/rwaldron/705311
*/
(function ($) {
// API for PubSub e.g. $.subscribe('example/test'); or $.publish('example/test', function (event, results) {});
var pubSub = {
'subscribe': 'on',
'unsubscribe': 'off',
'publish': 'trigger'
},
store = $({});
$.each(pubSub, function (callback, api) {
// Apply the likes of $.subscribe() or $.publish() to jQuery
$[callback] = function () {
// When called then invoke the jQuery versions e.g. .on() or .trigger()
store[api].apply(store, arguments);
};
});
})(jQuery);
// Demo
// A simple demo of how to use the following PubSub module
// DO NOT USE ANONYMOUS FUNCTIONS AS YOU WILL BE UNABLE TO UNSUBSCRIBE
function fireFirst() {
console.log('fireFirst: %o', arguments);
}
function fireSecond(_, arg1) { // _ = event, therefore this can be ignored
console.log('fireSecond: %o', arguments);
console.log('Arguments: %s', arg1);
}
// Subscribe to an event and bind a callback for each by passing a function reference
$.subscribe('search/twitter', fireFirst);
$.subscribe('search/twitter', fireSecond);
// Publish the event
$.publish('search/twitter', ['Example arg1', 'Example arg2']); // Must be an array of arguments
// Look in the browser's console
// Destroy the event only for the second function by passing the event name and the function reference i.e. fireSecond (no parentheses)
$.unsubscribe('search/twitter', fireSecond);
// Publish the event
// Notice how there is only one console.log() displayed, which is for the fireFirst() function
$.publish('search/twitter', ['Example arg1', 'Example arg2']); // Must be an array of arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment