The World’s Largest Ball of Events [architect]

If you try to unwind the flow of control through your $broadcast()/$emit()/$on() and keep losing your place, you have too many events*. Events (or “PubSub” or whathaveyou) are tools to use when you either don’t know or don’t care what’s listening to the event. In other words, if you expect that emitting your event calls function mayo() in SandwichCtrl, you’ve misused this pattern. This pattern is especially handy to use in libraries, so applications can listen and take appropriate action.

Find your events. Make a sequence diagram if you need to. Because any component can use $on(), there are simply too many permutations to address, but I can offer some guidelines:

Be especially wary of $broadcast()s whose sole purpose is to call a child Scope member function from a parent Scope. These are potentially the most troublesome; they are difficult to refactor and one of the more egregious misuses of this pattern. See “Complex Controller Hierarchies” above.
If you’re broadcasting from $rootScope, see if you can reign it in a little to a more appropriate context.
$rootScope is the AngularJS equivalent of the window object–the less stuff in $rootScope, the better.
If you’re $emit()ing on $rootScope, I’m sorry.
If you have a raucous crowd of emitters and broadcasters, and few listeners, you may have overengineered. Delete.
In the general case, try to use a service, factory, or communicate between directives. Call functions explicitly. You could even change routes if it makes sense!
The object here is not to annihilate all events. The flow between your emitters and listeners should be transparent, and ideally you won’t have many chains.

Leave a Reply