My question is regarding best practices between using a more direct callback structure vs. event broadcasting and listening. I had not been using the broadcast/emit/on event propagation framework. Rather I had been creating a callback register and firing registered callbacks when a known event occurs (at the source of the event). This is all done via services.
How efficient is the broadcast/emit/on paradigm? Should I be using it instead? Is it as efficient as the callback type of structure?
Thanks.
The difference between $broadcast() and $emit() is that the $broadcast() sends the event from the current controller to all of its child controllers. The $emit() method sends an event from current controller to all of its parent controllers.
Broadcast: We can pass the value from parent to child (i.e parent -> child controller.) Emit: we can pass the value from child to parent (i.e.child ->parent controller.) On: catch the event dispatched by $broadcast or $emit .
As you can see, the service object uses $rootScope. $emit() to announce interval events and the directive uses $rootScope. $on() to listen for those events.
$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.
It's less a question of efficiency but rather maintainability. When you use emit and broadcast you are coupling your mechanisms for communication to the view because the $scope
is fundamentally a fabric for data-binding. The services approach is far more maintainable because you can test the communication without spinning up a scope and can communicate between services in addition to controllers. With $scope
$broadcast
and $emit
you are only ever able to communicate where there is a $scope
you can inject.
After more than a year of developing mobile applications with angular here is what I would say: It is not an issue of using services or not. It is an issue about what is the best way to design communication between your services and your controllers ( or other services ). In short, both callback or promise based communication AND event messaging have a role. Event messages are great if you are assured that the listener will be available to receive the message when it is broadcast. In general, event messages and event listeners "feel" like a cleaner and more maintainable paradigm. However, if I have a controller that is going to "request" some data from a service, I find resolution via Promises ( or callbacks if you prefer ) to be cleaner in those situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With