$emit, $broadcast, $on – Part2

$emit: It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast: It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on: It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

  • And now creating the script, here myController is the controller which is going to emit/broadcast an event with some arguments.
  • parentController1, parentController2 will listen to event which is dispatched from myController by $broadcast.
  • childController1, childController2 will listen to event which is dispatched from myController by $emit.

 

output

  • In this example we have used $scope context to $emit/$broadcast the events, and $on has listened all the events by using $scope.$on().
  • Now if we have used $rootscrope context to $emit/$broadcast, it will not work same as that works with $scope.
  • Because $rootscope is the parent scope and it doesn’t have any parent, when we emit using $rootscope.$emit(), only $rootscope.$on() can listen to that events. Whereas when we broadcast using $rootscope.$broadcast(), all the $rootscope.$on() and $scope.$on() can listen to that event.

 

 

Cancelling Events:

Canelling event is possible when event is emitted, but we cannont cancel the event when it is broadcasted.

  • If the event is dispatched by using $scope.$emit( ) then any of the $rootscope/$scope listeners can cacel it.
  • If the event is dispatched by using $rootscope.$emit() then any of the $rootscope listeners can cancel it.

$emit, $broadcast, $on – Part1

One thought to “$emit, $broadcast, $on – Part2”

Leave a Reply

Your email address will not be published. Required fields are marked *