Interpretation of the eslint warning

I played a little with ES6 and angular and I use eslint-plugin-angular to test my javascript. I have the following service:

 export function runBlock ($rootScope, $state, $log) { 'ngInject'; $rootScope.$on( '$stateChangeStart', function(event, toState) { // ... } ); 

But eslint gives me the following error:

 The "$on" call should be assigned to a variable, in order to be destroyed during the $destroy event 

I mean, I understand the warning, but I never did this in my previous angular projects, should I do what the error suggests? Why is it necessary / good practice?

The docs for eslint-plugin-angular referenced by John Papa angular styleguide , but I really did not find any mention of this situation.

+7
javascript angularjs eslint
source share
1 answer

Not only does johnpapa styleguide not mention this situation, in fact it includes an example of ignoring the return of $rootScope.$on . However, a discussion of one of the eslint-plugin-angular issues clarifies the intention a bit:

If the controller registers the listener with $rootScope , it should probably be destroyed manually in " $destroy ", since the root area will survive all the controllers. - davidmason

This post also indirectly refers to "Guidelines should clean up after themselves" best practices from AngularJS documentation .

So, bottom line: a regular $scope object will eventually be destroyed when its controller executes and takes event listeners with it (assuming you haven't made any circular references that keep it in scope). $rootScope never dies and therefore never releases its event handlers. If your controller adds an event listener to $rootScope , it must remove the handler in your $destroy controller.

+8
source share

All Articles