Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created September 9, 2016 19:18
Show Gist options
  • Save gartenfeld/750140a27e377e98f90f2a3b4786b125 to your computer and use it in GitHub Desktop.
Save gartenfeld/750140a27e377e98f90f2a3b4786b125 to your computer and use it in GitHub Desktop.
A minimal PubSub
(function($) {
if (!$ || typeof $.extend !== 'function') {
console.info("No jQuery found. Plugin did not mount.");
return;
}
var _cache = {};
/**
* @param {string} topic
* @param {[]} args - An array of arguments passed to subscribers
*/
function publish(topic, args) {
(_cache[topic] || []).forEach(function() {
this.apply($, args || []);
});
}
/**
* @param {string} topic
* @param {Function} callback
* @return {object} A handle representing the subscription
*/
function subscribe(topic, callback) {
_cache[topic] = _cache[topic] || [];
_cache[topic].push(callback);
return {
topic: topic,
callback: callback
};
}
/**
* @param {object} sub
* @param {string} sub.topic
* @param {Function} sub.callback
*/
function unsubscribe(sub) {
var foundAt = (_cache[sub.topic] || []).indexOf(sub.callback);
if (foundAt !== -1) {
_cache[sub.topic].splice(foundAt, 1);
}
}
$.extend({
publish: publish,
subscribe: subscribe,
unsubscribe: unsubscribe
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment