0

I am creating a messaging service in angularjs project I am working.

(function (angular) {
    'use strict';

    angular.module('MyApp').factory('messagebus', messagebus);
    messagebus.$inject = ['$rootScope'];

    function messagebus($rootScope) {
        var factory = {
            publish: publish,
            subscribe: subscribe,
        };

        return factory;

        function publish(name, params) {
            $rootScope.$emit(name, params);
        }

        function subscribe(name, listener) {
            return $rootScope.$on(name, listener);
        }
    }
}(angular));

When I am calling the service this is what I am doing

var unregister = messagebus.subscribe('eventname', function (event, message) {
    // do something
});

$scope.$on('$destroy', function () {
    unregister();
});

I am handling unregistering part in the calling controller.

Is there something I can do in the messagebus service as a generic pattern and un register from there rather than calling unregister at each controller ?

C1pher
  • 1,933
  • 6
  • 33
  • 52
rednerus
  • 401
  • 2
  • 9
  • 21
  • 1
    Your message bus doesn't add much to what the scope already provides. If the controller called $on() on its own scope rather than the root scope, and if the publish function used $broadcast() instead of $emit(), you wouldn't have to unregister: the listener would disappear with the controller scope. – JB Nizet Aug 13 '15 at 16:50
  • Thanks for the response. You are right if I use $scope everything happens by default. But I am just starting on messaging service at $rootscope level so that it can be used across controllers. I wanted to build a global messaging service to exchange messages across controllers. – rednerus Aug 13 '15 at 17:31
  • 1
    That's exactly what the scope.$on and rootScope.$broadcast allow already. – JB Nizet Aug 13 '15 at 17:55

0 Answers0