Skip to content

Instantly share code, notes, and snippets.

@nmcgann nmcgann/pub-sub.js
Created Feb 10, 2017

Embed
What would you like to do?
Simple JS Pub-Sub implementation. Synchronous or Asynchronous.
/*
* Simple Publish / subscribe events routine.
*
* Used to extend an object with the subscribe and publish methods.
* The return value of subscribe has a remove method that can be used
* to unsubscribe.
*
* Modifies the object directly.
*/
var $$ = $$ || {}; //This is the utility functions object used elsewhere.
$$.pubSub = function(el) {
//Extend the original object or create a new empty one
el = el || {};
var topics = {};
Object.defineProperties(el, {
subscribe: {
value: function(topic, listener, synchronous) {
// Create the topic's base object if not yet created
if(!topics.hasOwnProperty(topic)){
topics[topic] = [];
}
// Add the listener to queue
var index = topics[topic].push({listener: listener, synchronous: !!synchronous}) - 1;
// Provide handle back for removal of topic
return { remove: function() {
delete topics[topic][index];
}
};
}
},
publish: {
value: function() {
var args = Array.prototype.slice.call(arguments, 0),
topic = args.shift(); //topic is 1st arg
// If the topic doesn't exist, or there's no listeners in queue, just leave
if(!topics.hasOwnProperty(topic)){
return;
};
// Cycle through topic subscribers and call with args
//synch or asynch alternatives
topics[topic].forEach(function(item) {
if(item.synchronous){
item.listener.apply(null,args);
}else{
setTimeout(function(){
item.listener.apply(null,args);
}, 0);
}
});
}
}
});
return el;
};
/* end */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.