At the time of writing, Salesforce has not exposed a means by which Lightning Web Components that are not nested within one another or even known by one another can communicate. For Lightning Aura components, these are called application events. While Salesforce works on closing this feature gap, the sample code in this chapter is utilizing a small utility library.
The pubsub component contains a utility library provided by Salesforce within their own code samples (at the time of writing) to demonstrate how inter-component communication can be achieved between loosely coupled components that may not be in the same parent-child hierarchy.
When users of the Race Overview page click on races in the Race Calendar, the Race Results component is automatically updated to show the applicable race results (you can try this out for yourself by clicking on Italy). These two components are not contained within one another; they are simply placed on the same Lightning page together. The publication and subscribe event pattern is ideal for this communication requirement.
The raceCalendar.js controller imports the pubsub library fireEvent method and calls it when a race is clicked. The following lines of code highlight these two aspects. The raceCalendar.js file is as follows:
// Import the pubsub utility library
import { fireEvent } from 'c/pubsub';
// Code within the handleSelect method
fireEvent(
this.pageRef, 'raceSelected',
{ raceId: raceId, raceName: raceName });
The raceResults.js controller imports the pubsub library registerListener and unregisterAllListeners methods. These methods are called by the following methods to subscribe and unsubscribe to the event during component creation and deletion.
Here is raceResults.js:
connectedCallback() {
registerListener('raceSelected', this.handleRaceSelected, this);
}
disconnectedCallback() {
unregisterAllListeners(this);
}
The handleRaceSelected method updates two properties that are tracked by the framework. When changes occur in those properties, this triggers calls to Apex and updates to the component's UI. We will discuss communication with Apex later in this chapter:
handleRaceSelected(race) {
this.raceId = race.raceId;
this.raceName = race.raceName;
}