简体   繁体   中英

eslint warning interpretation

I've been playing around a bit with ES6 and angular and I'm using eslint-plugin-angular to validate 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've never done this in my previous angular projects, should I have done what the error suggests? Why is it needed/good practice?

The docs for eslint-plugin-angular reference John Papa's angular styleguide , but I didn't really find a mention of this situation there.

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

If a controller is registering a listener on $rootScope it should probably be manually destroyed in " $destroy " since root scope will outlive all the controllers. -- davidmason

That post also indirectly references the "Directives should clean up after themselves" best practice from the AngularJS documentation .

So bottom line: A regular $scope object will eventually be destroyed when its controller does, and take its event listeners with it (assuming you haven't done any kind of circular referencing that keeps it in scope). $rootScope never dies, and therefore never releases its event handlers. If your controller is adding an event listener to $rootScope , it should remove that handler in your controller's $destroy handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM