Angularjs pubsub vs $broadcast Angularjs pubsub vs $broadcast javascript javascript

Angularjs pubsub vs $broadcast


I don't think you are missing anything. You've successfully outlined the pros/cons of each approach.

The $broadcast/$on approach doesn't require you to unsubscribe, but it is not terribly efficient as it broadcasts to all the scopes. It also has a very low barrier to entry. You don't need to inject any services, you don't need to create them. They broadcast to everyone, so it is a more simple approach.

The pub/sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work. It is more complex, however, because you need to write your service with callback handlers, and you have to remember to unsubscribe. The remembering to unsubscribe is pretty huge in my opinion. If you don't get this right, you get memory leaks. And you won't know it until it is a problem in 3 months.

I can see why the built-in approach is $broadcast.


I was looking at this same problem. Particularly how to allow services to broadcast and subscribe to events without accessing $rootScope (bad for a few reasons).I utilized the very excellent js-signals implementation from here :http://millermedeiros.github.io/js-signals/and wrapped it into an angular service.

github gist here : https://gist.github.com/anonymous/b552c7fafa77427e6d06