3

I know events can be very ugly fast, but is there a good way to manage or control the string names of events, so programmers will not be able to give the same string name event while working on different components?

Aviv M
  • 319
  • 1
  • 2
  • 12
  • I have a [wrapper created to manage the publish/subscribe in this answer of mine)](http://stackoverflow.com/questions/25274563/angularjs-communication-between-directives/25274665#25274665) without having to inject `$rootScope` (which i was annoyed about especially communicating with siblings and components that appear in a different hierarchy). Probably you could implement that kind of a wrapper and place the event name check... – PSL Aug 20 '14 at 13:14
  • @PSL thank you, I liked your service. Can I also subscribe to events with $scope and not $rootScope inside the service? Passing the scope as argument? – Aviv M Sep 06 '14 at 14:28
  • You mean inside the pubsub service ? The point of placing it in rootscope is that you have the method available in any `$scope`s except for isolated scope since they are not inherited. But you should be able to inject the service and pass in scope calling initialize – PSL Sep 07 '14 at 02:07

2 Answers2

3

The simplest way to do that things: just write your wrapper, that will register events

This is just example of idea

angular.service("EventManager", function($rootScope){

  var events_names = {};

  return {
      on: function(name, cb){
        if(!events_names[name]){
            $rootScope.$on(name, cb);
        }
        else{
            console.error("This kind of event already defined!", name);
        }
      }
  }  
});
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
2

There's no angular way to do so. But you could always write a wrapper fro $broadcast/$emit that has a registry for your event names.

Julian Hollmann
  • 2,902
  • 2
  • 25
  • 44