Rolando
Rolando

Reputation: 62596

Is it best practice in angular to wrap $rootScope broadcast and on in its own function?

My angularjs application depends heavily on $rootScope.$on and $rootScope.broadcast. Does it make any sense to have the $rootScope.broadcast be wrapped in its own factory as opposed to calling $rootScope.broadcast directly? I can see the benefits of having the subscribing $on being in its own factory such that you don't have to do $rootScope.$on, though I am not sure about the broadcast.

Different directives listen on different events on the $rootScope in my case, and not everything is used. DirectiveA has its own events, DirectiveB may have an overlapping set, DirectiveC may have events completely different from DirectiveA and B. The post seems to suggest putting all $rootScope events into a single service/"CoreReactorChannel" as the article below describes.

What prompted the question was reading this article: http://eburley.github.io/2013/01/31/angularjs-watch-pub-sub-best-practices.html

It also bothers me that the function CoreChannelReactor appears to be "global".

At the bottom: "Best practices around pub/sub:" they show essentially all the on and broadcast code that is directly tied to $rootscope in its own service/factory.

Does this design pattern have any benefits in performance or practice over injecting $rootScope directly into multiple services, directives, etc.?

Upvotes: 1

Views: 560

Answers (2)

Keith Rousseau
Keith Rousseau

Reputation: 4475

The major advantage of the pattern is consolidating your handling for a given event. It's basically combining an event source and handler into one object instead of having that logic spread out all over your app.

Upvotes: 1

HankScorpio
HankScorpio

Reputation: 3651

I don't know about "Best practice" in this case, but that's what we do here. Ours is called EventBus, and it supports a few extra things like having different event channels to avoid collisions in custom events and logging events that are broadcast when there are no listeners.

In short, it can be useful, and I recommend it.

Another advantage of having this kind of abstraction is you can change the implementation of your events system more easily when it's all centralized. For example, I recommend using $rootScope.$emit rather than $rootScope.$broadcast. That way, the even doesn't have to cascade down the $scope chain to all $scopes. It only cares about the ones listening at the $rootScope level.

Upvotes: 1

Related Questions