Skip to content

Instantly share code, notes, and snippets.

@absturztaube
Last active April 28, 2017 22:32
Show Gist options
  • Save absturztaube/859b49bdcca5d5b5434b42fab8c2415a to your computer and use it in GitHub Desktop.
Save absturztaube/859b49bdcca5d5b5434b42fab8c2415a to your computer and use it in GitHub Desktop.
Angular Observer Factory
var ngObserver = angular.module('ngObserver', []);
ngObserver.filter('hashCode', function() {
return function(input, hasType) {
if(hasType == null) {
hasType = false;
}
var result = typeof input;
var raw_hash = 0;
var mod_input = input;
if(typeof input === 'function') {
mod_input = input.toString();
}
if(typeof mod_input === 'string') {
var hash = 0, i, chr, len;
for (i = 0, len = mod_input.length; i < len; i++) {
chr = mod_input.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
result += '(' + hash + ')';
raw_hash = hash;
}
if(hasType) {
return result;
}
return raw_hash;
}
});
ngObserver.factory('Observer', ['hashCodeFilter', function(hashCodeFilter) {
return function() {
return angular.copy({
observers: {},
register: function (callback) {
this.observers[hashCodeFilter(callback)] = callback;
},
deregister: function (callback) {
delete this.observers[hashCodeFilter(callback)];
},
fire: function (sender, args) {
angular.forEach(this.observers, function (callback) {
callback(sender, args);
});
}
});
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment