Angularjs pubsub vs $broadcast

后端 未结 2 1907
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 02:16

I\'ve been reading up on event passing in Angularjs and I\'m not convinced that using $broadcast is a good idea.

Blogs like this one advocate getting used to $on eve

相关标签:
2条回答
  • 2020-12-09 02:42

    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.

    0 讨论(0)
  • 2020-12-09 02:42

    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

    0 讨论(0)
提交回复
热议问题