Created
February 10, 2017 16:38
-
-
Save nmcgann/6548ddd6b414349c0ad925d06428d610 to your computer and use it in GitHub Desktop.
Simple JS Pub-Sub implementation. Synchronous or Asynchronous.
This file contains hidden or 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
/* | |
* 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