Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active November 5, 2015 16:30
Show Gist options
  • Save erkobridee/28bdf6e7a4e91cd98caf to your computer and use it in GitHub Desktop.
Save erkobridee/28bdf6e7a4e91cd98caf to your computer and use it in GitHub Desktop.
(function(){
'use strict';
function PubSubService(){
/**
* based on: http://davidwalsh.name/pubsub-javascript
*/
var topics = {};
//----------------------------------------------------------------------------
//--- @begin: internal logic
function checkProperty(topic){
return (topics.hasOwnProperty.call(topics, topic));
}
function subscribers(topic){
if(!checkProperty(topic)){
return [];
} else {
return topics[topic];
}
}
function findIndexOf(topic, listener){
if(!checkProperty(topic)){
return -1;
} else {
return topics[topic].indexOf(listener);
}
}
function unsubscribe(topic, listener){
var index = findIndexOf(topic, listener);
if(index > -1){
topics[topic].splice(index, 1);
}
index = null;
}
function subscribe(topic, listener){
// Create the topic's object if not yet created
if(!checkProperty(topic)){
topics[topic] = [];
}
if(findIndexOf(topic, listener) > -1){
// listener already registered
return;
}
// Add the listener to queue
topics[topic].push(listener);
listener.unsubscribe = function internalUnsubscribe(){
unsubscribe(topic, listener);
topic = null;
listener = null;
};
return {
unsubscribe : listener.unsubscribe
};
}
function publish(topic, data){
// If the topic doesn't exist, or there's no listeners in queue, just leave
if(!checkProperty(topic)){
return;
}
// Cycle through topics queue, fire!
topics[topic].forEach(function(item) {
item(data);
});
}
//--- @end: internal logic
//----------------------------------------------------------------------------
//--- API
return {
subscribers : subscribers,
subscribe : subscribe,
unsubscribe : unsubscribe,
publish : publish
};
}
// PubSubService.$inject = [];
angular
.module('app')
.factory('PubSubService', PubSubService);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment