global communication in angular module: event bus or mediator pattern/service

前端 未结 3 1486
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 22:51

So far I have seen many solutions of the problem. The simplest one is, of course, to $emit an event in $rootScope as an event bus e.g. ( https://gi

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 23:56

    Creating your own implementation of event emitter is counter-productive when writing an AngularJS application. Angular already provides all tools needed for event-based communication.

    • Using $emit on $rootScope works nicely for global inter-service communication and doesn't really have any drawbacks.
    • Using $broadcast on a natural scope (one that is bound to a part of your DOM) provides scoped communication between view components (directives, controllers).
    • Using $broadcast on $rootScope brings the two previous points together (it provides a completely global communication platform). This is the solution used basically by any AngularJS-based library out there.

    and

    • If you're worried about performance in the previous option and you really want your separate event emitter, you can easily create one by creating an isolated scope ($rootScope.$new(true)) and using $broadcast on it. (You can then wrap it into a service and inject it anywhere you want.)

    The last option creates a full-fledged event emitter integrated into Angular (the implementation provided in your question would at least need to wrap all listener calls in $apply() to integrate properly) that can be additionally used for data change observation, if that fits a particular use-case.

    However, unless your application is really humongous, or you're really paranoid about event name collisions, the first three options should suffice just fine.


    I won't go into detail about other means of communication between your components. Generally speaking, when the situation calls for data sharing using scope, direct interaction of controllers, or communication through DOM Node attributes, you should know it.

提交回复
热议问题