Last active
August 29, 2015 14:07
-
-
Save mockdeep/857f00477978e811f214 to your computer and use it in GitHub Desktop.
javascript pub/sub
This file contains hidden or 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 = {}; | |
function getQueue(topic) { | |
topics[topic] = topics[topic] || []; | |
return topics[topic]; | |
} | |
return { | |
subscribe: function(topic, listener) { | |
var index = getQueue(topic).push(listener) - 1; | |
}, | |
remove: function(topic, listener) { | |
queue = getQueue(topic); | |
index = queue.indexOf(listener); | |
delete queue[index]; | |
}, | |
publish: function(topic, info) { | |
if(!topics[topic] || !topics[topic].queue.length) return; | |
var items = topics[topic].queue; | |
getQueue(topic).forEach(function(listener) { | |
listener(info || {}); | |
}); | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment