Created
June 12, 2014 19:00
-
-
Save hwclass/11c85272efdda84c36ff to your computer and use it in GitHub Desktop.
A Pub / Sub Sample
This file contains 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
var events = (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); | |
// Provide handle back for removal of topic | |
return (function(index) { | |
return { | |
remove: function() { | |
delete topics[index]; | |
} | |
} | |
})(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 x = 0; x < items.length; x++) { | |
items[x](info || {}); | |
} | |
} | |
}; | |
})(); | |
/*initialize an event subscription*/ | |
var testSub = events.subscribe('/page/load', function(obj) { | |
console.log('test sub callback after /page/load occurs.'); | |
}); | |
/*publish an event*/ | |
events.publish('/page/load', { | |
url: '/some/url/path' // any argument | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment