1

I've been using $broadcast a lot in my application and I'm doing some optimiations right now and I'm wondering if I should keep using $scope.$broadcast (or $emit) for my inter-service and inter-directive communications or swith to a custom-made message bus.

The problem is that I've been shoehorning $rootScope in a lot of services that don't have anything to do with it other than to listen for scope events.

Bogdan
  • 1,869
  • 6
  • 24
  • 53
  • It's all too easy to get carried away optimizing things that aren't a problem. Have you profiled the application to see where the time is being spent? – Michal Charemza Sep 26 '14 at 07:28
  • You're right. While, at the moment, my uses of scope events is sparse and driven by user actions (on form submits, navigation, etc) I might not want to spend time optimizing in this case. The question remains tho. Also I would like to use something that doesn't involve using $rootScope where it's only use is event listening/broadcasting. – Bogdan Sep 26 '14 at 07:42

1 Answers1

1

Prefer $emit than $broadcast beacuse the first one is more fast.

Use a service where you can instead events to share datas between controllers.

Take a look at popstaljs, I use this library in my last application and works pretty well (http://jonathancreamer.com/an-angular-event-bus-with-postal-js/).

There are a lot of posts about $broadcast vs $emit, like What's the correct way to communicate between controllers in AngularJS?

Community
  • 1
  • 1
originof
  • 795
  • 1
  • 7
  • 24
  • I thought they fixed $broadcast to not bubble into all the scopes.(besides, I need it to communicate from $rootScope to a descendant) I'll take a look at postaljs to see how I can use it. Thanks – Bogdan Sep 26 '14 at 07:10
  • 2
    AFAIK, [$emit](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit) and [$broadcast](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast) are not used for the same purposes, since $emit dispatches an event upwards while $broadcast dispatches an event downwards... – sp00m Sep 26 '14 at 07:11
  • @originof I had a look at postal-js and the article you linked, and I have to wonder, have you used it yourself? It seems kinda bloat-y but I guess it's faster than $broadcast in most cases. Also the implementation in the article seems to tie it to scope. I need to communicate between services that don't have a scope (shoehorning the $rootScope comes to mind again) – Bogdan Sep 26 '14 at 07:17
  • I have a FatherController and a lot of ChildrensController and SiblingsControllers that communicate each others using postaljs. In this way I can separate communications and make the code more readable using the channels and topics feature. – originof Sep 26 '14 at 07:21