Search code examples
angularjs-serviceangularjs-factory

angular event listener


I'm working on a huge project for a client, so to make the code cleaner, i'm doing some rework. I'm having this part of code :

var removeListener = $rootScope.$on('logoutEvent', function () {
    changedAttribut = EditorialContentService.getChangedAttribut($scope.promotion, OLDPromo, hasUploadImage);
    if (changedAttribut.length < 1) {
        $rootScope.canClose = true;
    } else {
        $rootScope.canClose = false;
    }
});
$scope.$on("$destroy", removeListener);

The thing, is that, I need to put the code inside a service or a factory or any other suggestions, to avoid duplication, because it is used in many controllers.


Solution

  • Either call

    $rootScope.$on("$destroy", removeListener);
    

    (instead of $scope), which will remove the listener when the whole app is destroyed (but that's not really needed, because events registered with $on are automatically removed when the scope they were registered on is destroyed), or expose a function from the factory that removes the listener, and call it when the appropriate scope destroys:

    // inside the factory
    return {
        destroy: function () {
            removeListener();
        }
    };
    
    // inside the appropriate controller
    $scope.$on('$destroy', thatFactory.destroy);