Skip to content

Instantly share code, notes, and snippets.

@ryardley
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryardley/ed0245ca1f89bd20e49d to your computer and use it in GitHub Desktop.
Save ryardley/ed0245ca1f89bd20e49d to your computer and use it in GitHub Desktop.
angular.module('utils.ElementRegistryDemo',[])
.directive('elem', function(ElementRegistry) {
return {
restrict: 'A',
scope: false,
link:function(scope, element, attrs){
// store this element with reference to the parent scope
new ElementRegistry(scope).add(attrs.elem, element);
}
};
})
.factory('ElementRegistry', function () {
var id, // scope id to store on the class
waitingFor={}; // dictionary of callbacks we are waiting for
function ElementRegistry(scope){
id = scope.$id;
// initialize class stores if they are undefined
ElementRegistry.store = ElementRegistry.store || {};
ElementRegistry.store[id] = ElementRegistry.store[id] || {};
}
// get a key from the store
function findByKey(key){
return ElementRegistry.store[id][key] ? ElementRegistry.store[id][key] : false;
}
// hold on to a call back until it is needed
function storeCallback(key, callback){
waitingFor[key] = callback;
}
// run the stored callback
function fireCallback(key){
if(waitingFor[key]){
waitingFor[key](findByKey(key));
}
}
ElementRegistry.prototype = {
// return the found value otherwise run a callback once found
find: function(key, callback){
var found = findByKey(key);
if(!found){
storeCallback(key, callback);
return;
}
if(callback){
callback(found);
}
return found;
},
// add an element to the scope store
add: function(key, value){
ElementRegistry.store[id][key] = value;
fireCallback(key);
},
// return the storage object
store: function(){
return ElementRegistry.store[id];
}
};
return ElementRegistry;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment