Let’s explore.
- Decorators
- DispatchEvent and CustomEvent
- QuerySelectors
- Import/Export
- Spread Notation
- Slots
- Promises
- String Interpolation combined with Let/Const declarations
Decorators:
Decorators serve as directives for the compiler, specifying actions to be performed with the code. Similar to how we utilize “@AuraEnabled” in Apex code for Aura components.
For Lightning Web Components (LWC), the following decorators are commonly employed:
- @track:
This decorator facilitates internal communication within components, ensuring the privacy of values while enabling reactivity. Using @track, you instruct the compiler to monitor changes between the backend and frontend activities. For instance, when modifying inputs “a” and “b” in a simple calculation (e.g., “a + b = c”), updates made in the frontend result, “c,” need to reflect backend modifications promptly. - @api:
By default, components are private. However, by applying the @api decorator, you expose specific elements to external access, rendering them public and reactive. This enables external entities to invoke and interact with these elements as needed. - @wire:
This decorator is a reactive data service, facilitating seamless integration of functions and variables with data sources. It establishes connections between components and data, ensuring real-time updates and synchronization.
These decorators play a pivotal role in implementing Salesforce Lightning Web Components, enabling efficient development and robust functionality.
DispatchEvent and CustomEvent:
DispatchEvent and CustomEvent are integral components of web standards, facilitating the transmission of events from child to parent elements. It’s noteworthy that the event naming convention dictates the use of ‘on‘ preceding the event name. Therefore, it’s advisable to exclude ‘on‘ from your event name to avoid conflict with reserved keywords such as ‘onchange‘ utilized within markup as an event handler.
Syntax Example:
childCmp.js
const changeEvent = new CustomEvent('change', {detail: this.roles}); this.dispatchEvent(changeEvent);
parentCmp.html
<c-role-filter onchange={handleRoleChange}> </c-role-filter>
Here, the ‘onchange‘ attribute in the parent component handles the ‘change‘ event from the child component. Additionally, to facilitate data exchange between these components, we employ the @api decorator within our code.
QuerySelector:
In traditional client-side JavaScript within Lightning components, we’ve often employed Document.getElementById. However, it’s important to note that this method isn’t viable within Lightning Web Components (LWC) due to security considerations.
Instead, of adhering to modern web standards, LWC adopts QuerySelector as a robust alternative.
Consider the following example:
card.html
<template>
Hey! Welcome to the: {name}
</template>
In the markup, the ‘card‘ is defined within the template.
card.js
import { api, LightningElement } from 'lwc';
export default class card extends LightningElement { @api name = "Salesforce"; }
- The value of ‘name‘ is defined as ‘Salesforce‘ using @api.
cardContainer.html
<c-card></c-card>
- The ‘card‘ component is called within the markup of the ‘cardContainer‘ component.
cardContainer.js
let card = this.template.querySelector("c-card"); card.name = "SF";
- Within the controller, ‘querySelector‘ retrieves the ‘c-card‘ component.
- Subsequently, the value is reassigned as “SF” to the ‘card‘ variable. OUTPUT:
Import/Export:
The Import/Export mechanism in ECMAScript 6 serves as a crucial feature for integrating external helper functions seamlessly into your codebase, akin to employing libraries. This functionality extends beyond solely LWC imports, allowing the inclusion of custom libraries as well.
For instance, to harness functionalities such as ‘API’ or ‘track’, the syntax is as follows:
// Importing necessary modules and functions
import { LightningElement, track, api } from 'lwc'; // Importing from LWC
import getAccountList from '@salesforce/apex/accController.getAccountList'; // Importing Apex class function
import { flatten } from 'c/jsUtils'; // Importing from an external library
// Exporting a function
export function flatten(obj, prefix=[], current={}) {
// Function implementation here
}
This mechanism enables efficient organization and modularization of code, fostering reusability and maintainability across your Lightning Web Components and beyond.
Spread Notation:
Spread notation, introduced in ECMAScript 9, offers a method to explicitly duplicate data from one array into another during utilization.
Key points to note:
- It facilitates the creation of arrays, consequently updating tracked variables within Lightning Web Components.
- The spread notation effectively disassembles frontend elements when transferring values between arrays.
Syntax Example:
this.data = [...result1, ...result2];
In this syntax, the ‘…’ symbol denotes the spread notation, enabling seamless integration of data from ‘result1‘ and ‘result2‘ arrays into the ‘data’ array.
Slots:
Slots represent another fundamental web standard, facilitating the passing of HTML content to a component.
Let’s check this example:
Consider a ‘greeting‘ component:
greeting.html
<template>
He is from: <slot name="country"></slot>
We called him: <slot name="name"></slot>
</template>
In another component, define the values:
greetingContainer.html
<c-greeting>
<span slot="country">US</span>
<span slot="name">Salesforce</span>
</c-greeting>
OUTPUT:
He is from: US
We called him: Salesforce
In essence, slots enable the insertion of content into components, providing a seamless method for content inclusion.
Assurances:
Assurances offer a paradigm for managing data communication synchronously, ensuring a structured approach to handling asynchronous operations. By awaiting the completion or failure of tasks, Assurances signify a commitment to act upon the eventual outcome.
Assurances are characterized by their usage of .then(), .catch(), and .finally() methods, which respectively handle successful execution, errors, and clean-up operations. This parallels the behavior of Lightning components, where responses trigger specific actions based on success or failure.
Let’s elucidate with an example:
let Assurance = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Happy learning');
}, 2000);
});
Assurance.then(function (result) {
console.log('Salesforce said: ' + result);
}).catch(reason => {
console.log('Assurance rejected: ' + reason);
});
// Console result will be:
// Console > Salesforce said: Happy Learning
It’s important to note that when dealing with multiple Assurances, Assurance.all() is employed to manage them collectively.
While the syntax provided adheres to ECMAScript 6 standards, higher versions like ECMAScript 8 introduce Async/Await syntax, although the underlying concept remains consistent.
String Interpolation (ECMAScript) + Let/Const:
In Lightning Aura components, concatenation has been a common practice for joining multiple strings. However, transitioning to Lightning Web Components necessitates a shift in approach.
For instance:
console.log('string1' + 'string2' + 'string3');
Now, we’re encouraged to embrace interpolation. Let’s illustrate this with an example:
function favouriteBlogs() {
let firstBlog = 'Salesforce Official';
const secondBlog = 'Salesforce';
// String Interpolation below
console.log(`My First or Second blogs are ${firstBlog} and ${secondBlog}`);
}
// Console > My First or Second blogs are Salesforce Official and Salesforce
As depicted, we simply utilize ${variable}
within the string instead of concatenation.
Let/Const: While ‘var‘ has been the norm in traditional JavaScript, the advent of Let/Const ushers in a more disciplined approach.
Let:
- Used when reassignment of variable values is necessary.
- Implies that the variable’s scope is confined to the block it’s declared in, rather than the entire function.
Const:
- Employed when a variable’s value remains constant and cannot be reassigned.
- Ensures the identifier remains immutable.