I am using angular-js. I have a service that need to trigger event each time something occurs. For doing it I need an object that will act as event aggregator
.
$rootScope
? $rootScope
, how can I ensure that there is no event names conflicts? $rootScope
for events that don't need them to propagate to child scopes? I modeled and implemented the following mechanism in a web project for tablets:
Define notifications in your services. I did not want to use the term events since I did not want it to be confused with DOM events by other developers in my team. And a semi-typed name for a notification is easier for IDE with intellisense support and for debugging. For example, I have one Device
service that would $broadcast(Device.Notification.OrientationDidChange)
when a tablet device's orientation is changed.
Use Scope
objects to $broadcast
or $emit
notifications, depending on your need. For example,
$rootScope.$broadcast(Device.Notification.OrientationDidChange)
. So all listeners can listen on their own scope without injecting $rootScope
.scope.$broadcast(UI.Notification.NeedsLayout)
, where UI
is a predefined service to hold UI related constants, and scope
is the current scope.rangeStart
value has changed (in addition to regular two way binding), I use: scope.$emit(Slider.Notification.RangeStartDidChange)
, where scope
is the current scope.This approach is a bit verbose in a small project. You might want to stick to using $rootScope.$emit(Notification)
all the time, and let all listeners to do $rootScope.$on(Notification, callback)
to receive these notifications.
In some situations, you might want to define these notifications in a centralized service in order to more easily avoid name conflicts. It really based upon your project's naming convention.
The implementation (actual values) of these notifications may vary. I prefer using strings
.
With $broadcast
or $emit
you can also actually pass additional arguments to the listeners, for example, $broadcast(Notification, arg1, arg2)
... Angular's documentation is quite detailed.
Take a look at http://docs.angularjs.org/api/ng.$rootScope.Scope#$broadcast
.
$rootScope
as event aggregator is perfectly fine unless you are triggering events outslide digest cycle
or triggering multiple (100+) events at the same time where some other solutions may be more appropriate .namespace:event
- pattern used by Backbone.Marionette
)$emit
on a child scope instead of $broadcast
on $rootScope
- $emit
propagates only upwards, where $broadcast
propagates downwards - to all childrenIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With