Skip to content

Instantly share code, notes, and snippets.

@phusick
Created June 12, 2014 19:37
Show Gist options
  • Save phusick/3eec19b56cb7c8e82ce4 to your computer and use it in GitHub Desktop.
Save phusick/3eec19b56cb7c8e82ce4 to your computer and use it in GitHub Desktop.
Event Hub
<html>
<head>
<title>Event Hub</title>
<script src="hub.js"></script>
<script>
var subscription = hub.subscribe('/go', function(params) {
console.log('one', params);
});
var subscription2 = hub.subscribe('/go', function(params) {
console.log('two', params);
});
hub.subscribe('/extra', function(params) {
console.log('extra', params);
});
</script>
</head>
<body>
<button id="go">go</button>
<button id="unsubscribe1">unsubscribe 1</button>
<button id="unsubscribe2">unsubscribe 2</button>
<script>
var d = document;
d.getElementById('go').addEventListener('click', function(event) {
hub.publish('/go', event.timeStamp);
});
d.getElementById('unsubscribe1').addEventListener('click', function() {
console.log('unsubscribe 1');
subscription.remove();
});
d.getElementById('unsubscribe2').addEventListener('click', function() {
console.log('unsubscribe 2');
subscription2.remove();
});
</script>
</body>
</html>
var hub = (function(){
var topics = {};
return {
subscribe: function(topic, listener) {
// Create the topic's object if not yet created
if(!topics[topic]) topics[topic] = { queue: [] };
// Add the listener to queue
var index = topics[topic].queue.push(listener) - 1;
// Provide handle back for removal of topic
return (function(topic, index) {
return {
remove: function() {
delete topics[topic].queue[index];
}
}
})(topic, index);
},
publish: function(topic, info) {
// If the topic doesn't exist, or there's no listeners in queue, just leave
if(!topics[topic] || !topics[topic].queue.length) return;
// Cycle through topics queue, fire!
var items = topics[topic].queue;
for(var i = 0, len = items.length; i < len; i++) {
if(typeof items[i] === 'function') items[i](info || {});
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment