$eventBus
Description
A messaging service, backed by an instance of
PubSub. This implementation is based on
the original
Google Closure PubSub
but uses
Promise.resolve()
instead of
Window.setTimeout()
for its async implementation. $eventBus allows communication between an
Angular application instance and the outside context, which can be a different
module, a non-Angular application, a third-party party library, or even a WASM
application. Additionally, $eventBus can be used to communicate directly with
a template, using ng-channel directive.
$eventBus should not be used for communicating between Angular’s own
primitives.
- For sharing application state: use custom Services and Factories that encapsulate your business logic and manage your model.
- For intercomponent communication: use
$scope.$on(),$scope.$emit(), and$scope.$broadcast()methods.
The example below demonstrates communication between the global window context
and a controller. Note: Ensure topic clean-up after the $scope is
destroyed
Example
<section ng-app="demo">
<div ng-controller="DemoCtrl as $ctrl">
Milliseconds elapsed since the epoch <b>{{ $ctrl.ms }}</b>
</div>
</section>
<!--We are using a regular onclick and `angular` global -->
<button
class="btn btn-dark"
onclick="angular.$eventBus.publish('demo', Date.now())"
>
Publish time
</button>
window.angular.module('demo', []).controller(
'DemoCtrl',
class {
static $inject = ['$eventBus', '$scope'];
constructor($eventBus, $scope) {
const key = $eventBus.subscribe('demo', (val) => {
// `this.ms = val` will not work because `this` is not a proxy
// to trigger change detection, we access controller as a scope property
$scope.$ctrl.ms = val;
});
$scope.$on('$destroy', () => $eventBus.unsubscribeByKey(key));
}
},
);
Demo
For detailed method description, see PubSub
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.