Skip to content

Instantly share code, notes, and snippets.

@jrencz
Created May 16, 2014 08:48
Show Gist options
  • Save jrencz/f1107bb2432672996dbe to your computer and use it in GitHub Desktop.
Save jrencz/f1107bb2432672996dbe to your computer and use it in GitHub Desktop.
Simple way to register many event handlers to AngularJS scope.
function traverse(scope, level, rootPath, delimiter) {
rootPath = rootPath || [];
Object.keys(level).forEach(function (key) {
const path = rootPath.slice(0);
path.push(key);
if (angular.isFunction(level[key])) {
scope.$on(path.join(delimiter), level[key]);
return;
}
traverse(scope, level[key], path, delimiter);
});
}
traverse($rootScope, {
foo: function fooHandler() {},
group: {
bar: function groupBarHandler() {},
baz: function groupBazHandler() {},
}
}, ['prefix'], '-');
// binds the following evet -> handler pairs
// prefix-foo -> fooHandler()
// prefix-group-bar -> groupBarHandler()
// prefix-group-baz -> groupBazHandler()
// to $rootScope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment