var pubSub = (function(){
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
};
}
return PubSubService();
})();
//------------------------------------------------------------------------------
// basic tests
var alohaFunction = function(params){ console.log('aloha function executed ', params); }
var listener = pubSub.subscribe('aloha', alohaFunction);
pubSub.subscribe('aloha', alohaFunction);
pubSub.publish('aloha', { name: 'erko', age: 31 });
console.log('aloha listeners ', pubSub.subscribers('aloha').length);
listener.unsubscribe();
pubSub.unsubscribe('aloha', alohaFunction);
console.log('aloha listeners ', pubSub.subscribers('aloha').length);
a simple pub sub js service
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.