Mister_L
Mister_L

Reputation: 2611

angular rootscope broadcast from a service

I heard its a bad practice to use rootscope $on from a controller, because when a controller is destroyed, the event listener is not. If I use it from a service and inject it to the controller, like below, will it prevent memory leaks?

.service("hiEventService",function($rootScope) {
    this.broadcast = function() {$rootScope.$broadcast("hi")}
    this.listen = function(callback) {$rootScope.$on("hi",callback)}
})

Upvotes: 2

Views: 1132

Answers (1)

Chanthu
Chanthu

Reputation: 1794

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

Upvotes: 2

Related Questions