import { LightningElement } from 'lwc';
export default class LifecycleDemo extends LightningElement {
constructor(){
super();
console.log('Constructor Called WHEN INSTANCE IS CREATED--1.NO DOM MANUPULATION 2.NO ATTRIBUTE VALUES ASSIGNEMENT POSSIBLE');
}
connectedCallback(){
console.log('Component Connected Callback is called --Now DOM is Inserted so 1.CAN ASSIGN ATTRIBUTE VALUES 2. CANNOT call querylocater and CANNOT MANUPULATE THE DOM here because DOM is NOT RENDERED yet');
}
renderedCallback(){
console.log('Component Rendered Callback is called---1 DOM is RENDERED so we can use querySelector 2. CAN ALSO MANUPULATE THE DOM');
}
disconnectedCallback(){
console.log('Component DisConnected Callback is called--1.CALLED WHEN NAVIGATING TO OTHER PAGE --- 2. ');
}
}
----------------INTER COMPONENT COMMUNICATION--------------
COMPONENT 1:
tileClickHandler(){
fireEvent(this.pageReference, 'pubsubtileclick', this.meetingRoomInfo);
}
COMPONENT 2:
connectedCallback(){
registerListener('pubsubtileclick', this.onMeetingRoomSelectHandler, this);
}
so when we use pubsub registerListener in a component then registerListener method doesnt need to be always called only once and it will keep listning always in LWC ?
ChatGPT said:
Yes, in Lightning Web Components (LWC), the registerListener function is generally set up only once per component, and it keeps listening as long as the component is in the DOM.
Here's how it works in practice:
One-Time Setup: When you call registerListener (typically in the connectedCallback of your component), it registers the event listener for the specific event name and callback. This registration persists as long as the component is in the DOM.
Persistent Listening: The listener will keep listening for any events of that specific type (e.g., updates, clicks, etc.) and will trigger the callback whenever such an event occurs in the pubsub.
Automatic Cleanup: It’s a best practice to call unregisterAllListeners in the disconnectedCallback of the component. This helps to avoid memory leaks when the component is removed from the DOM, as it unregisters all event listeners associated with that component.
Here’s an example of the typical setup:
In this setup, registerListener is only called once in connectedCallback. It keeps listening for myEvent as long as the component is active, and stops when disconnectedCallback calls unregisterAllListeners.
Comments
Post a Comment