Angular JS, Understanding $emit, $broadcast and $on

Angular JS, Understanding $emit, $broadcast and $on

In late 2015 I started working with Angular JS as part of a project at work (Hybrid mobile app).

Understanding the concepts is quite important to make use of it in an efficient and extendable way.

Angular JS provides us with some events that we can use to communicate between controllers.

They are $on, $emit and $broadcast.

Here is a quick schematic on the direction of the events.

on-emit-broadcast-angular-js

$on

When using $on, Angular listens to an event of a given type. We can call it anyway we want. $on will catch any event dispatched by $emit or $broadcast.

Real life example from a hybrid app:

$scope.$on(AUTH_EVENTS.notAuthorized, function(event) {
 //do something to block the unauthorized page view attempt
 });
});

(AUTH_EVENTS is a constant we are using in our app)

So what happens and how / where does this happen?

In an authentication service, the user is checked if logged in. If he / she is not, we will emit an event which will block the unauthorized page view.

So we need to broadcast this event:

$scope.$broadcast('AUTH_EVENTS.notAuthorized', { ... });

Since we mentioned broadcast, let’s quickly go through that.

$broadcast

Broadcast dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

$broadcast(name, args);

The event cannot be cancelled. The event starts at the scope on which $broadcast was called. All listeners for the event get notified, all events under the scope.

$emit

 is pretty much the same thing, just in reverse (going upwards into the $scope).

It will traverse all the $scopes until the $rootScope.

Unlike the $broadcast event, this one can be cancelled by any of the listeners.

Do try to keep the $rootScope clean 🙂


Tags: