How do I listen to application events?
From a component or view
export class MyView extends View {
protected onBeforeRender(): void {
this.listen('language-changed', () => console.log('language changed'));
this.listenToRenderEvents(['language-changed']); // re-render whenever it fires
}
}
this.listen(event, callback)(available on every component/view) subscribes and automatically unsubscribes it on destroy. Prefer this over callingAppEventBus.subscribedirectly, which has no automatic cleanup.this.listenToRenderEvents([...events])is a shortcut that re-renders the component whenever any of the given events fire - usesthis.listenunder the hood.
Directly via AppEventBus
import { AppEventBus } from '../../../core/index.js';
AppEventBus.subscribe('language-changed', (data) => console.log(data.lang));
AppEventBus.once('language-changed', (data) => { /* fires once, then auto-unsubscribes */ });
AppEventBus.emit('language-changed', { lang: 'fr' });
AppEventBus.off('language-changed', callback); // omit callback to remove ALL handlers for that event
subscribe/oncereturnvoid, not an unsubscribe function — to unsubscribe you must callAppEventBus.off(event, callback)yourself with the same callback reference. This is whythis.listen(...)(which handles that bookkeeping for you) is preferred inside a component/view.
See How do I emit events? for adding your own typed events to EventMap.