Fundamentals - Cheat Sheet VII

The Event Aggregator

- If you include the aurelia-event-aggregator plugin using "basicConfiguration" or "standardConfiguration" then the singleton EventAggregator's API will be also present on the Aurelia object. 
- You can also create additional instances of the EventAggregator, if needed, and "merge" them into any object. To do this, import includeEventsIn and invoke it with the object you wish to turn into an event aggregator. 
- For example includeEventsIn(myObject). Now my object has publish and subscribe methods and can be used in the same way as the global event aggregator, detailed below.

Publishing on a Channel 
import {inject} from 'aurelia-framework'; 
import {EventAggregator} from 'aurelia-event-aggregator'; 

@inject(EventAggregator) 
export class APublisher { 
           constructor(eventAggregator) { 
                              this.eventAggregator = eventAggregator;  
           } 
           publish(){  
                       var payload = {};  
                       this.eventAggregator.publish('channel name here', payload); 
           } 
}

Subscribing to a Channel
import {inject} from 'aurelia-framework';  
import {EventAggregator} from 'aurelia-event-aggregator'; 

@inject(EventAggregator)  
export class ASubscriber { 
           constructor(eventAggregator) {  
                              this.eventAggregator = eventAggregator;  
           } 
           subscribe() {  
                          this.eventAggregator.subscribe('channel name here', payload => { 
                                 ... 
                          }); 
           } 
}

Publishing a Message
//some-message.js  
export class SomeMessage{ } 

//a-publisher.js  
import {inject} from 'aurelia-framework';  
import {EventAggregator} from 'aurelia-event-aggregator';  
import {SomeMessage} from './some-message'; 

@inject(EventAggregator) 
export class APublisher {  
           constructor(eventAggregator) { 
                              this.eventAggregator = eventAggregator; 
           } 
           publish() { 
                       this.eventAggregator.publish(new SomeMessage());  
           } 
}

Subscribing to a Message Type
import {inject} from 'aurelia-framework'; 
import {EventAggregator} from 'aurelia-event-aggregator'; 
import {SomeMessage} from './some-message'; 

@inject(EventAggregator)  
export class ASubscriber {  
           constructor(eventAggregator) {  
                              this.eventAggregator = eventAggregator;  
           } 
           subscribe(){  
                          this.eventAggregator.subscribe(SomeMessage, message => {  
                                 ... 
                          });  
          } 
}        

Comments

Popular posts from this blog

Fundamentals - App Config & Startup - VIII

Fundamentals - Dependency Injection V

Style vs Css attribute