Skip to content

Instantly share code, notes, and snippets.

@mkropat
Last active July 31, 2016 19:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkropat/6de4e1dc3a9577789917 to your computer and use it in GitHub Desktop.
Save mkropat/6de4e1dc3a9577789917 to your computer and use it in GitHub Desktop.
Automatic trace logging of Angular.js events and ui-router state transitions
angular.module('your-module').config(['$provide', function ($provide) {
$provide.decorator('$rootScope', ['$delegate', function ($delegate) {
wrapMethod($delegate, '$broadcast', function (method, args) {
if (isNonSystemEvent(args[0]))
logCall('$broadcast', args);
return method.apply(this, args);
});
wrapMethod($delegate, '$emit', function (method, args) {
if (isNonSystemEvent(args[0]))
logCall('$emit', args);
return method.apply(this, args);
});
return $delegate;
function isNonSystemEvent(eventName) {
return eventName && eventName[0] && eventName[0] !== '$';
}
}]);
$provide.decorator('$state', ['$delegate', function ($delegate) {
wrapMethod($delegate, 'go', function (method, args) {
logCall('$state.go', args);
return method.apply(this, args);
});
return $delegate;
}]);
function wrapMethod(obj, methodName, wrapper) {
var original = obj[methodName];
obj[methodName] = function () {
var args = Array.prototype.slice.call(arguments, 0);
return wrapper.call(this, original, args);
};
}
function logCall(funcName, args) {
var prettyArgs = args.map(function (a) { return repr(a) })
.join(', ');
console.log(funcName + '(' + prettyArgs + ')');
}
function repr(obj) {
return JSON.stringify(obj, function (k, v) {
if (k !== '' && v instanceof Object)
return '[Obj]';
else
return v;
});
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment