Sub topic 3
Sharing Data Across Namespaces with Public Properties and Events
Assume you know LWC structure, modern JavaScript, DOM boundaries, namespaces, and static resources. At a namespace boundary, do not access another component’s DOM or global variables. Use public properties and custom events.
Sharing Data Across Namespaces
A public property is a component value marked with @api. A custom event is a message that a child sends to its parent. Pass plain data in the event’s detail value.
import { LightningElement, api } from 'lwc';
export default class ItemPicker extends LightningElement {
@api label;
handleSelect() {
this.dispatchEvent(
new CustomEvent('select', { detail: { id: '001' } })
);
}
}The parent binds a value to label and listens for select. Keep event data serializable and document the event contract. This pattern remains valid when the components belong to different namespaces.
Third-Party Libraries and CSP
Load a third-party library from a Salesforce static resource with loadScript. Initialize it after loading, and query only elements in your own template.
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import LIBRARY from '@salesforce/resourceUrl/library';
export default class LibraryHost extends LightningElement {
loaded = false;
async renderedCallback() {
if (this.loaded) return;
this.loaded = true;
try {
await loadScript(this, LIBRARY);
// Initialize the library with this.template elements here.
} catch (error) {
console.error('Library failed to load', error);
}
}
}LWS runs the library inside the component’s namespace sandbox. A library that depends on unrestricted globals, browser source rewriting, or cross-component DOM access may fail.
Migrating and Troubleshooting
Enable LWS in a sandbox first. Test namespace boundaries, DOM queries, third-party libraries, and browser APIs before production. Replace Locker-specific workarounds with standard JavaScript. Do not assume that code working under Locker is secure or portable under LWS.
When an error appears, identify whether it comes from your component, the library, CSP, or a denied API. Check the browser console, isolate the smallest failing operation, and test with a supported library version. Change application code when it violates a boundary. Replace the library when it requires forbidden access.
Exercise
How should a child component in another namespace send a selected record identifier to its parent?
Show answer
Dispatch a custom event whose detail contains the identifier. Do not access the parent’s DOM or globals.