Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept all $rootScope.$broadcast events in angular.js

I have potentially multiple $rootScope.$broadcast events affecting one view element. I would like to have a hierarchical function to decide which event takes precedence for effecting the view.

My question is, how can I listen to all events $broadcasted on the $rootScope? Is there some kind of event interceptor?

like image 975
roscioli Avatar asked Dec 09 '22 04:12

roscioli


1 Answers

I was searching for solutions for the same problem. Came across caitp's solution at https://github.com/angular/angular.js/issues/6043 which I believe is what you were looking for as well.

This has the advantage that you can leave it in development and simply not include it in production code, without changing any logic in you application.

I'll copy the code from the link for posterity, with minor adjustments (to work with current versions of angular):

app.config(function($provide) {
    $provide.decorator("$rootScope", function($delegate) {
    var Scope = $delegate.constructor;
    var origBroadcast = Scope.prototype.$broadcast;
    var origEmit = Scope.prototype.$emit;

    Scope.prototype.$broadcast = function() {
      console.log("$broadcast was called on $scope " + this.$id + " with arguments:",
                     arguments);
      return origBroadcast.apply(this, arguments);
    };
    Scope.prototype.$emit = function() {
      console.log("$emit was called on $scope " + this.$id + " with arguments:",
                     arguments);
      return origEmit.apply(this, arguments);
    };
    return $delegate;
    });
});

More info about $provide.decorate:

[1] http://blog.xebia.com/extending-angularjs-services-with-the-decorate-method/

[2] https://docs.angularjs.org/api/auto/service/$provide

like image 65
Adrian B. Avatar answered Dec 11 '22 12:12

Adrian B.