Event Dispatching in Angular
AngularJS provides an Event dispatching system allowing the communication between controllers or services and controllers.
$broadcast dispatches the event downwards through the child scopes
$emit dispatches the event upwards through the scope hierarchy
$on catches the event passing by that scope
You can usually see it being used from $rootScope or $scope
$scope.$broadcast('eventName', arg);
$rootScope.$broadcast('eventName', arg);
$scope.$emit('eventName', arg);
$rootScope.$emit('eventName', arg);
$scope.$on('eventToCatch', function);
$rootScope.$on('eventToCatch', function);
Now, there are a few things to know about using it from $rootScope:
- Both
$rootScope.$emitand$rootScope.$broadcastgo through child scopes since$rootScopedoesn't have a parent $rootScope.$emitcan only be received by$rootScope.$on$rootScope.$broadcastcan be received by$rootScope.$onand$scope.$on$rootScope.$onlistener needs to be removed by hand (Memory leak if forgotten)
How we are using it in the project
- Usage of event dispatching should be limited if possible
- We only use
$rootScope.$broadcastand$scope.$onfor event dispatching/catching - We are grouping all the
$scope.$onfunctions at the end of the compponent using it (controller or service)
Performances
Using $broadcast might not seem optimum if we consider the description we have above.
However, it is optimized to only go through branches that have a matching event binding. (cf. this post)