User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Events in AngularJS - $emit, $broadcast & $on

Hi friends, Events are so popular concepts in every programming language. In AngularJS we have also some events which help us to communicate between different Controllers.

We have the following events in our AngularJS:

$on: It helps us to listen the $broadcast & $emit events in AngularJS.

$broadcast: It helps us to dispatches the event downwards to all child scopes

$emit: It helps us to dispatches the event upwards with their scope hierarchy.


We will understand these events with some scenario. Let start with first scenario. Parent-Child relation between Controller


Look at the following code:

  1. var myModule=angular.module('myModule', []);
  2. myModule.controller('ParentCtrl','['$scope',function($scope){
  3. $scope.$broadcast('childEvent', [1,2,3]);
  4. }]);
  5. myModule.controller('ChildCtrl','['$scope',function($scope){
  6. $scope.$on('childEvent', function(event, paramValue) { console.log(paramValue); });
  7. }]);



In the above code we can understand the concept of events in AngulaJS with Parent-Child relation. Now move ahead and start with other scenario.


Let start with second scenario. There is no parent child relationship between scope, in that case we need to inject $rootScope into the controller and broadcast the event to all child scopes.


Look at the following code:

  1. myModule.controller('MainCtrl','['$scope','$rootScope'function($scope,
  2. $rootScope){
  3. $rootScope.$broadcast('displayEvent', [1,2,3]);
  4. }]);
  5. myModule.controller('OtherCtrl','['$scope',function($scope){
  6. $scope.$on('displayEvent', function(event, paramValue) { console.log(paramValue); });
  7. }]);


In the above discussion we can understand the different scenarios with the help of sample code. Now move ahead and start discussion about some other events.

$emit: It is use to dispatches the event upwards with their scope hierarchy.

$emit always follow the parent-child relationship in upwards direction. - See more at: http://firstcrazydeveloper.com/Blogs/BlogView.html/50/events-in-angularjs-emit-broadcast-and-on#sthash.3yEwSl7W.dpuf

$emit: It is use to dispatches the event upwards with their scope hierarchy.

$emit always follow the parent-child relationship in upwards direction. - See more at: http://firstcrazydeveloper.com/Blogs/BlogView.html/50/events-in-angularjs-emit-broadcast-and-on#sthash.3yEwSl7W.dpuf

$emit: It helps us to dispatches the event upwards with their scope hierarchy and always follow the parent-child relationship in upwards direction.


So, let start with some difference between $rootScope.$emit and $rootScope.$broadcast

 $rootScope hasn't any $parent, in this case an $emit would be pointless. Here $rootscope.$emit will fire an event for all $rootScope.$on listeners. The important part here is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners.


I think in the above discussion we tried to understand the some complex scenarios. For better understanding we start with some real examples with some identified points:


1. If we talk about $rootScope.$emit, this only lets other $rootScope listeners to catch it. Good to use when we don't want every $scope to get it. Generally it is a high level communication between each other, like some top level management talking to each other in cabin so the other employee can't hear them.

2. If we talk about $rootScope.$broadcast, this is a method that lets pretty much everything hear it. It's a simple like teacher yelling that open your notebook so everyone in the classroom hears it.

3. If we talk about $scope.$emit, this is when we want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their mother at home (but not in market where other kids can hear).

4. If we talk about $scope.$broadcast, this is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.


After all of the above discussion move ahead and start with some important point which create issues when we use these functionality so we need carefull with this events.


1. $rootScope live forever in application scope so if our Controller is run multiple time then all $rootScope.$on inside  it will run all time whenever Controller called and caught events will result in callback invoked multiple times. If we use $scope.$on instead of $rootscope.$on, the callback will be surly destroyed along with our controller implicitly by AngularJS application. This is a common cause of bugs in an AngularJS application.


2. If we must need to use $rootscope.$on in our application, in that case we need to manually destroy that on Controller  destroy event.

Look at the sample code:

  1. var cleanListeneEvents = $rootScope.$on('someEvent', function(event, paramValue) { console.log(paramValue); });
  2. $scope.$on('$destroy', function() {
  3. //this will deregister that listener
  4. cleanListeneEvents();
  5. });


3. We should Always prefer $rootScope.$emit() instead of $rootScope.$broadcast(). Because whenever we $broadcast on $rootScope, event is bubbled down to every scope currently existing. That can be make slow our application. It's not necessary to do that, if our listeners are hooked to $rootScope.


4. If In rare case we need to use these events, instead of this we can use Service and inject with Controller/ Directive to communicate with each other. If we need to communicate changes all over our application use a service to maintain the values and load the values when the various views are active.



5. If we know that there is only one listener, and we have already encountered it, we can stop further propagation of the event by calling event.stopPropagation() on the event object passed to the event listener function.



6. The worst part is that 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



7. If we talk about performance, then $emit() is faster than $broadcast().

After the above discussion I hope we can understand the concepts of these events in AngularJS. Now let look some Pros and Const:

Pros:

1.)  Easy way to communicate between different Controllers.

Const:

1.)  Not easy way to track the flow of an application.

2.)  Decrease performance.

3.)  When we use $rootScope then need to manually destroy.

This is all what I know and hope this will help you in future when you start event based coding in AngularJS. Most welcome if you have any suggestion.


Happy reading!!

Abhishek Kumar


crazydeveloper Home Page 29 May 2015

Become a Fan