I don't think this is going to 'prevent' memory leaks because it never gets destroyed through out the lifetime of the application because every even is getting registered on $rootScope
.
Best practice would be to destroy the listener on scope destruction.
For example, if there is a controller that's listening to an event like so,
$scope.$on('anEvent', function(){});
there is no need to destroy the listener as the listeners will be automatically unregistered on scope destruction, automatically.
On the other hand if the event is registered on $rootScope
,
var eventHandle = $rootScope.$on('anEvent', function(){});
the even can be (and should be) destroyed by executing the eventHandle
(which is a function) on scope destroy:
$scope.$on('$destroy', function(){
eventHandle();
});
And also, try to avoid broadcasting events on $rootScope
. Try using $emit
and $broadcast
on child scopes. More info: $rootScope.$broadcast vs. $scope.$emit