tabs

Thursday, October 17, 2013

$broadcast (), $emit() and $on() in Angular Js

In order to understand how the events are propagated along the html DOM we use few functions that raise the events and others which behave as their listeners. Sometimes we require to enable only the parent scope elements get affected from the current scope and sometimes vice-versa.
In order to meet these two situations angular provides some event raisers and event listeners.

Event Raisers:

$broadcast(eventName, arguments) and
$emit(eventName, arguments)
//Both these functions can raise an event and can send arguments too.

Event Listener:

$on(eventName, listener)
This function gets executed whenever the respective ‘eventName’ is raised and the ‘listener’ is a function that gets executed whenever it listens to an event from the event raisers.
Now let us know about them in detail:
$broadcast(): It dispatches the event name to the registered listeners of scope downwards the current scope and their child scopes i.e. the event propagates or traverses from the scope where the event is raised to all the child scopes with valid listeners on it.

$emit(): It dispatches the event name to the registered listeners of the scope upwards from the current scope along the way to the root scope .The event traverses through all the listeners from the current scope to the parent scopes on its way to the root scope.
Let us check with an example:
Here is my html page:

Here is my javascript:
function myController($scope) {
    $scope.count = 0;
    $scope.$on('MyEvent', function () {
        $scope.count++;
    });
}
Just replicate the above code in your visual studio.Once you run it it looks like this:
  • Click on the Emit-Event button, it means that we are generating an event using $emit() in the middle scope i.e the current scope from where the event is originated.
    Now the output looks like this:
    Observation:The count in the current scope and the parent scope are incremented to 1.
    As discussed earlier the $emit() dispatched the event name to the listeners in the scope upwards the current scope .So the parent scope is incremented.
  • Now click on the Broadcast-Event button, it means that we are raising an event using $broadcast() in the mid scope ie in the current scope.
    Now the output looks like:
    Observation: The current scope and the leaf scopes are incremented whereas the parent scope remains unchanged.
    Here , $broadcast() dispatched an event which traverses to the listener downwards the current scope.
Hope this helps you to understand the very basic actions of $broadcast,$emit and $on.Please feel free to comment and your valuable suggestions are always welcome.

No comments:

Post a Comment