Subscribing to events

GoMeddo Floorplan uses the Lightning Message Service for some of its events. You can subscribe to two message channels to receive a message when one of these events happens.

Message channels

  • FP25__Area_Selected__c publishes a message when an area is selected. The message contains selectedAreaId, the ID of the selected area.

  • FP25__DateTime_Selected__c publishes a message when a date and time is selected. The message contains selectedDateTime, the selected date and time, and showFutureOccupancies. It's true when Future Occupancy View is selected and false when Date View is selected.

Example

This Lightning web component subscribes to FP25__Area_Selected__c and stores the ID of the selected area:

JavaScript
import { LightningElement, wire } from 'lwc';
import {
    subscribe,
    unsubscribe,
    APPLICATION_SCOPE,
    MessageContext,
} from 'lightning/messageService';
import areaSelectedChannel from '@salesforce/messageChannel/FP25__Area_Selected__c';

export default class Floorplan extends LightningElement {
    subscription = null;
    selectedAreaId;
    areaSubscription;

    @wire(MessageContext)
    messageContext;
    
    // Encapsulate logic for Lightning message service subscribe and unsubscribe
    subscribeToMessageChannel() {
        if (!this.subscription) {
            this.subscription = subscribe(
                this.messageContext,
                areaSelectedChannel,
                (message) => this.handleMessage(message),
                { scope: APPLICATION_SCOPE }
            );
        }
    }
  
    unsubscribeToMessageChannel() {
        unsubscribe(this.subscription);
        this.subscription = null;
    }

    // Handler for message received by component
    handleMessage(message) {
        this.selectedAreaId = message.selectedAreaId;
    }

    // Standard lifecycle hooks used to subscribe and unsubscribe to the message channel
    connectedCallback() {
        this.subscribeToMessageChannel();
    }

    disconnectedCallback() {
        this.unsubscribeToMessageChannel();
    }
}