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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…