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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With