Skip to content

Instantly share code, notes, and snippets.

@Grace
Forked from phusick/hub.html
Created December 9, 2015 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grace/d8ab102ee71310aa9e88 to your computer and use it in GitHub Desktop.
Save Grace/d8ab102ee71310aa9e88 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