Event Handling between Aura, Lightning Web Components (LWC) and Visualforce

Salesforce Lightning Message Service

Few months back, I wrote an article on how pub sub model can be used to communicate between Lightning Web Components. In that blog post, we used external library to pass event from child to Lightning Web Components.

Lightning Message Service

In Winter 20, Salesforce released Lightning Message Service which can be used to exchange data between Visualforce, Aura Component and Lightning Web Components. Unlike previous process, we don’t need to import any external library like pub or sub.

In this blog post, I would be creating Visualforce, Aura Component and Lightning Message Service and exchanging message between all of them using Lightning Message Service.

Lightning Web Component Event Handling – Pub Sub

Event Communication between Lightning Web Components

It is very common to come across use case of communicating between Lightning Web Components.

If you are not interested on code explanation and directly want to jump on live demo , check this playground.

Communicate between Nested Lightning Web Components

This is one of most simplest and common use case, where parent LWC wants to react on event produced by child LWC.

In above image, Model 3 is child (nested component) of Tesla.

Getting Started with Lightning Web Component

Before starting with Lightning Web Component, I would suggest to read this introduction post first.

If you enjoy watching video then you might enjoy below video where I conducted Live coding explaining basics of Lightning Web Component.

In this post, we are going to Show loading image on initial load of LWC. In background we would be calling Apex class to take decision if loading image should be hided or redirect user to some other page.

Get Current User Id in Salesforce

Quick Code Snippets of how to get Current logged in user ids in Salesforce


System.debug('Current User Id - '+UserInfo.getUserId());


  <h1>Visualforce Page</h1> 
   <p>UserId: {!$User.Id}</p>
   <p>User Email: {!$User.Email}</p>

Aura Component

let currentUser = $A.get("$SObjectType.CurrentUser.Id");

Lightning Web Components (LWC)

Using wire

import USER_ID from '@salesforce/user/Id';
import NAME_FIELD from '@salesforce/schema/User.Name';
import EMAIL_FIELD from '@salesforce/schema/User.Email';

Formula Fields