Skip to content

Instantly share code, notes, and snippets.

@element6
Last active November 13, 2015 03:22
Show Gist options
  • Save element6/6de6a89296f4f495afa6 to your computer and use it in GitHub Desktop.
Save element6/6de6a89296f4f495afa6 to your computer and use it in GitHub Desktop.
javascript pub/sub event helper
var events = (function() {
var topics = {};
return {
sub: function(topic, listener) {
topics[topic] = topics[topic] || [];
var index = topics[topic].push(listener) - 1;
// Provide handle back for removal of topic
return {
remove: function() {
topics[topic].splice(index, 1);
if (topics[topic].length === 0) delete topics[topic];
}
};
},
pub: function(topic, info) {
if (!topics.hasOwnProperty(topic)) return;
topics[topic].forEach(function(item) {
item(info || {});
});
}
};
})();
//angular has $boardcast and $on
//if running on browser, there is also webapi
//fire event
document.dispatchEvent(new CustomEvent('assetInstance/' + key, {detail: val}));
//subscribe event
var subAssetChange = function(event){
updateUI();
};
document.addEventListener('assetInstance/' + $scope.asset.flake_id, subAssetChange);
$scope.$on("$destroy", function() {
if (subAssetChange) {
document.removeEventListener('assetInstance/' + $scope.asset.flake_id, subAssetChange);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment