Why avoid using $rootScope.$broadcast() and use $rootScope.$emit() instead

bonsai
Mega Sage

The product documentation below states that you should avoid using "$rootScope.$broadcast()" and use "$rootScope.$emit()" instead.
Why is this?

I understand that these are used to pass values ​​between widgets.

 

 

https://www.servicenow.com/docs/bundle/yokohama-application-development/page/build/professional-deve...

1 ACCEPTED SOLUTION

Bhimashankar H
Mega Sage

Hi @bonsai ,

 

The recommendation to prefer $rootScope.$emit() over $rootScope.$broadcast() in AngularJS (which ServiceNow Service Portal uses) relates to how events propagate through the scope hierarchy and the impact on performance and maintain.

 

$rootScope.$broadcast()Downwards from root to all child scopes
$rootScope.$emit()Upwards from root scope (rarely used at root)

 

$broadcast() sends the event to every child scope in the app, which may be many scopes, potentially causing unnecessary listeners to execute and slowing down the app performance and speed.

 

$emit() propagates the event upwards through parent scopes, which is usually more targeted.  With $rootScope.$emit(), event listeners explicitly on $rootScope or its ancestors receive it, reducing noise.

 

Thanks,
Bhimashankar H

 

-------------------------------------------------------------------------------------------------
If my response points you in the right directions, please consider marking it as 'Helpful' & 'Correct'. Thanks!

 

View solution in original post

2 REPLIES 2

RaghavSh
Kilo Patron

It has performance issues.


Raghav
MVP 2023

Bhimashankar H
Mega Sage

Hi @bonsai ,

 

The recommendation to prefer $rootScope.$emit() over $rootScope.$broadcast() in AngularJS (which ServiceNow Service Portal uses) relates to how events propagate through the scope hierarchy and the impact on performance and maintain.

 

$rootScope.$broadcast()Downwards from root to all child scopes
$rootScope.$emit()Upwards from root scope (rarely used at root)

 

$broadcast() sends the event to every child scope in the app, which may be many scopes, potentially causing unnecessary listeners to execute and slowing down the app performance and speed.

 

$emit() propagates the event upwards through parent scopes, which is usually more targeted.  With $rootScope.$emit(), event listeners explicitly on $rootScope or its ancestors receive it, reducing noise.

 

Thanks,
Bhimashankar H

 

-------------------------------------------------------------------------------------------------
If my response points you in the right directions, please consider marking it as 'Helpful' & 'Correct'. Thanks!