LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Using the event aggregator
  • Subscribing to events
  • Publishing events
  • Disposing event listeners

Was this helpful?

Export as PDF
  1. Aurelia Packages

Event Aggregator

The Event Aggregator is a pub/sub event package that allows you to publish and subscribe custom events inside of your Aurelia applications. Some parts of the Aurelia framework use the event aggregator to publish certain events at various points of the lifecycle and actions taking place in the framework.

Using the event aggregator

To use the Event Aggregator, we inject the IEventAggregator interface into our component. In the following code example, we inject it as ea on our component class.

import { ICustomElementViewModel, IEventAggregator, resolve } from 'aurelia';

export class MyComponent implements ICustomElementViewModel {
    readonly ea: IEventAggregator = resolve(IEventAggregator);
}

Subscribing to events

The Event Aggregator provides a subscribe method to subscribe to published events.

import { ICustomElementViewModel, IEventAggregator, resolve } from 'aurelia';

export class MyComponent implements ICustomElementViewModel {
    readonly ea: IEventAggregator = resolve(IEventAggregator);

    bound() {
        this.ea.subscribe('event name', payload => {
            // Do stuff inside of this callback
        });
    }
}

In some situations, you might only want to subscribe to an event once. To do that, we can use the subscribeOnce method which will listen to the event and then dispose of itself once it has been fired.

import { ICustomElementViewModel, IEventAggregator, resolve } from 'aurelia';

export class MyComponent implements ICustomElementViewModel {
    readonly ea: IEventAggregator = resolve(IEventAggregator);

    bound() {
        this.ea.subscribeOnce('event name', payload => {
            // Do stuff inside of this callback just once
        });
    }
 }

Publishing events

To publish (emit) an event, we use the publish method. You can provide an object to the publish method which allows you to emit data via the event (accessible as a parameter on the subscribe method).

import { ICustomElementViewModel, IEventAggregator, resolve } from 'aurelia';

export class MyComponent implements ICustomElementViewModel {
    readonly ea: IEventAggregator = resolve(IEventAggregator);

    bound() {
        const payload = {
            component: 'my-component',
            prop: 'value',
            child: {
                prop: 'value'
            }
        };

        this.ea.publish('component bound', payload);
    }
}

Disposing event listeners

It's considered best practice to dispose of your event listeners when you are finished with them. Inside of a component, you would usually do this inside of the unbinding method. The event will be of type IDisposable which we will use to strongly type our class property.

import { ICustomElementViewModel, IEventAggregator, IDisposable, resolve } from 'aurelia';

export class MyComponent implements ICustomElementViewModel {
    private myEvent: IDisposable;

    readonly ea: IEventAggregator = resolve(IEventAggregator);

    bound() {
        this.myEvent = this.ea.subscribe('event name', payload => {
            // Do stuff inside of this callback
        });
    }

    unbinding() {
        this.myEvent.dispose();
    }
}
PreviousAdvancedNextState

Last updated 1 year ago

Was this helpful?