Last active
September 6, 2016 21:29
-
-
Save simonwoo/22c79f16c32219bc0e13acd47a6d6890 to your computer and use it in GitHub Desktop.
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 = {}; | |
return { | |
publish: function(topic, info) { | |
console.log('publish a topic:' + topic); | |
if (topics.hasOwnProperty(topic)) { | |
topics[topic].forEach(function(handler) { | |
handler(info ? info : {}); | |
}) | |
} | |
}, | |
subscribe: function(topic, handler) { | |
console.log('subscribe an topic:' + topic); | |
if (!topics.hasOwnProperty(topic)) { | |
topics[topic] = []; | |
} | |
topics[topic].push(handler); | |
}, | |
remove: function(topic, handler) { | |
if (!topics.hasOwnProperty(topic)) { | |
return; | |
} | |
var handlerIndex = -1; | |
topics[topic].forEach(function(element, index) { | |
if (element === handler) { | |
handlerIndex = index; | |
} | |
}); | |
if (handlerIndex >= 0) { | |
topics[topic].splice(handlerIndex, 1); | |
} | |
}, | |
removeAll: function(topic) { | |
console.log('remove all the handler on the topic:' + topic); | |
if (topics.hasOwnProperty(topic)) { | |
topics[topic].length = 0; | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment