4

I came across this post whilst reading up on the correct ways for cleaning up event listeners attached to $scope in angularjs.

I am listening to an event on $rootScope in my app module run block:

app.run(['$rootScope', function($rootScope){
  $rootScope.$on('$stateChangeStart', function(event, toState, toParams){
    //do stuff here...
  });
}]);

Since $scope is not available in the run block, can I listen for the destroy event on $rootScope instead?

So:

app.run(['$rootScope', function($rootScope){
  var listenerFn = $rootScope.$on('$stateChangeStart', function(event, toState, toParams){
    //do stuff here...
  });

  $rootScope.$on('$destroy', listenerFn);
}]);

I'm not so sure I can do it this way looking around various posts and docs online since it doesn't look like $rootScope has a destroy event. So what's the correct approach here?

Community
  • 1
  • 1
mindparse
  • 6,115
  • 27
  • 90
  • 191
  • 1
    _"Since $scope is not available in the run block"_ - It is, but it's called `$rootScope` ^^ _"it doesn't look like $rootScope has a destroy event"_ the root scope gets destroyed when you close or leave the page. Everything will be gone then, so there's nothing to clean up. – a better oliver Nov 27 '15 at 09:23
  • Yes ok, I did wonder if I needed to worry about it. The thing is, I'm actually using ESLint with this plugin enabled - https://github.com/Gillespie59/eslint-plugin-angular. It's throwing up a warning based on this rule - https://github.com/Gillespie59/eslint-plugin-angular/blob/master/docs/on-watch.md - Looks like I wont be able to get around this then. – mindparse Nov 27 '15 at 09:31
  • 1
    Since there's nothing to clean up you may as well disable the eslint rule on that line with `// eslint-disable-line angular/on-watch` – Carl Jun 30 '16 at 04:30

0 Answers0