Event aggregator should be used when your events need to be attached to more listeners or when you need to observe some functionality of your app and wait for the data update.
Aurelia event aggregator has three methods. The publish method will fire off events and can be used by multiple subscribers. For subscribing to an event, we can use the subscribe method. And finally, we can use the dispose method to detach the subscribers. The following example demonstrates this.
Our view will just have three buttons for each of the three functionalities.
<template> <button click.delegate = "publish()">PUBLISH</button><br/> <button click.delegate = "subscribe()">SUBSCRIBE</button><br/> <button click.delegate = "dispose()">DISPOSE</button> </template>
We need to import eventAggregator and inject it before we are able to use it.
import {inject} from 'aurelia-framework'; import {EventAggregator} from 'aurelia-event-aggregator'; @inject(EventAggregator) export class App { constructor(eventAggregator) { this.eventAggregator = eventAggregator; } publish() { var payload = 'This is some data...'; this.eventAggregator.publish('myEventName', payload); } subscribe() { this.subscriber = this.eventAggregator.subscribe('myEventName', payload => { console.log(payload); }); } dispose() { this.subscriber.dispose(); console.log('Disposed!!!'); } }
We need to click the SUBSCRIBE button to listen for data that will be published in future. Once the subscriber is attached, whenever new data is sent, the console will log it. If we click the PUBLISH button five times, we will see that it is logged every time.
We can also detach our subscriber by clicking the DISPOSE button.