Reputation: 3153
There are quite some advantages I see in flexibility and code reduction (you do not have to bind values across many layers of components) in using events but it could also complicate debugging.
My question
Is using $rootScope.$broadcast() in AngularJS 1.6 still a good practice to react on changes in models for example?
Upvotes: 1
Views: 1161
Reputation: 5978
I can't say for all angular developers, but I will try to use my own experience. Using $broadcast and especially $rootScope.$broadcast can have several negative side effects.
Performance. $rootScope broadcast will run through each component. It will rise and re-rise $digest that can cause freezes if you have to much $watchers.
Readability. Events break readability of your code.
Debug. Event driven model is a bit harder to maintain and debug. You should know your solution very well to find subscribers and debug them.
And angular gives you way to avoid this.
If you need to react on child node (scope, controller, etc) you can pass your model and use $onChanges method on controller
$onChanges?(changesObj: {[property:string]: IChangesObject}): void;
If you need to react on parent node, pass method to child and invoke it when something changes.
There is only one reason when you may use $broadcast - when you need to react on sibling node. Than it is much easier to broadcast event than make a chain with update -> update -> update.
Using $broadcast is a bit easier solution at the start but than it will hit your development performance. So it is just a meter of the price you are ready to pay and your current needs.
Hope this helps.
Upvotes: 1
Reputation: 10148
In angluar framework itself, there are only few events. So you can get an idea about why not to depend heavily on events, there is definitely other and better ways to do it.
You may face problems like
An event based approach can get really messy to track, maintain and debug. It makes it very asynchronous, with no real easy way to track the flow of an application.
It would be much difficult to work in team environment following broadcast
approach. And your code may/can error prone most of the times.
Moreover, there are very few cases when you need to Dispatches an event name downwards to all child scopes and if there is, you must know that
when you add an event listener on the $scope of a controller, when the controller is destroy (you navigate away from the page, or close a section), the listeners also get destroyed. When you add it to the $rootScope
, when you navigate away from a controller, the listener remains and keeps triggering. So you have to manually deregister it, or be safe and just not add it on $rootScope
.
Upvotes: 2