English 中文(简体)
Aurelia - Event Aggregator
  • 时间:2024-09-08

Aurepa - Event Aggregator


Previous Page Next Page  

Event aggregator should be used when your events need to be attached to more psteners or when you need to observe some functionapty of your app and wait for the data update.

Aurepa event aggregator has three methods. The pubpsh 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 functionapties.

app.html

<template>
   <button cpck.delegate = "pubpsh()">PUBLISH</button><br/>
   <button cpck.delegate = "subscribe()">SUBSCRIBE</button><br/>
   <button cpck.delegate = "dispose()">DISPOSE</button>
</template>

We need to import eventAggregator and inject it before we are able to use it.

app.js

import {inject} from  aurepa-framework ;
import {EventAggregator} from  aurepa-event-aggregator ;

@inject(EventAggregator)
export class App {
   constructor(eventAggregator) {
      this.eventAggregator = eventAggregator;
   }
   pubpsh() {
      var payload =  This is some data... ;
      this.eventAggregator.pubpsh( myEventName , payload);
   }
   subscribe() {
      this.subscriber = this.eventAggregator.subscribe( myEventName , payload => {
         console.log(payload);
      });
   }
   dispose() {
      this.subscriber.dispose();
      console.log( Disposed!!! );
   }
}

We need to cpck the SUBSCRIBE button to psten for data that will be pubpshed in future. Once the subscriber is attached, whenever new data is sent, the console will log it. If we cpck the PUBLISH button five times, we will see that it is logged every time.

Aurepa Event Aggregator Example

We can also detach our subscriber by cpcking the DISPOSE button.

Advertisements