Skip to main content
Skip table of contents

Subscribing to events

Floorplan is using the Lightning Message Service for some of its events. This means you could subscribe to two message channels that receive messages on the firing of a specific event.

  • The areaSelectedChannel publishes messages when an area is selected, and passes the selectedAreaId property;

  • The dateTimeSelectedChannel publishes messages when a datetime is selected, and passes the selectedDateTime property.

Sample code that listens to the areaSelected event:

NONE
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 unsubsubscribe
    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 unsubsubscribe to the message channel
    connectedCallback() {
        this.subscribeToMessageChannel();
    }

    disconnectedCallback() {
        this.unsubscribeToMessageChannel();
    }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.