Last active
November 13, 2015 03:22
-
-
Save element6/6de6a89296f4f495afa6 to your computer and use it in GitHub Desktop.
javascript pub/sub event helper
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 { | |
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