Last Updated: July 25, 2019
·
8.591K
· lperrin

10 lines of js to log all $emit events in AngularJS

$rootScope.$emit is a great way of propagating events around your app. This snippet will log them without touching to the rest of you app.

As your AngularJS app grows, you'll feel the need to split it into dozens of services, directives and controllers. $rootScope.$emit is a great way of sharing information with other modules: it does not make your modules require each other and it does not clutter scopes with global variables.

However, there are times when you'd like to know exactly which events you are sending. This will do it for you. I keep it commented somewhere close :).

myApp.config(['$provide', function ($provide) {
  $provide.decorator('$rootScope', function ($delegate) {
    var _emit = $delegate.$emit;

    $delegate.$emit = function () {
      console.log.apply(console, arguments);
      _emit.apply(this, arguments);
    };

    return $delegate;
  });
}]);

3 Responses
Add your response

Great article; thanks. A couple of questions for you though.

1) What does the .apply() methods do for both console.log and _emit()? I've tried looking in documentation but unable to find any .apply() methods mentioned

2) I tried augmenting the $broadcast event using the exact same pattern, but get errors with it. Is there a specific reason why this would not work with the $broadcast event?

TypeError: Cannot read property 'defaultPrevented' of undefined
at http://localhost:58888/client.git/bower_components/angular/angular.js:10171:88

Thanks,
Eric

over 1 year ago ·

Hi Eric,
yes I run in the same issue. The problem is, that $broadcast and $emit have return values!

You can simply use my Gist here: https://gist.github.com/sebastianzillessen/3d2cea1aa5d6433aa2ac

Happy Coding!

over 1 year ago ·

it should be:
return _emit.apply(this, arguments);
instead of:
_emit.apply(this, arguments);
otherwise $broadcast API like $rootScope.$broadcast("foo", "bar").defaultPrevented will throw NPE

over 1 year ago ·