Create and Dispatch Events
Create and dispatch events in a component’s JavaScript class. To create an event, use the constructor. To dispatch an event, call the
EventTarget.dispatchEvent()
method.
The
CustomEvent()
the constructor has one required parameter, which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. However, we recommend that you confirm with the DOM event standard.
Communicate from child to grand parent.
Child.html
<template>
<button onclick={updateparent} >Update Prnt and Grand Parent</button>
</template>
Child.js
import { LightningElement,api} from 'lwc';
export default class Child extends LightningElement {
@api recordData;
updateparent(){
this.dispatchEvent(new CustomEvent('updateme',
{bubbles: true,composed: true,detail:"John"}
));
}
}
parent.html
<template>
<my-child record-data={objdata} onupdateme={prntfun}></my-child>
<
</template>
parent.js
import { LightningElement, track} from 'lwc';
export default class Prnt extends LightningElement {
@track objdata=[
{"firstname":"Mark", "lastname":"Paul",
"Picture":"https://techcrunch.com/wp-content/uploads/2019/08/Screen-Shot-2019-08-29-at-3.02.46-PM.png?w=1390&crop=1" },
{"firstname":"Jennie", "lastname":"Paul",
"Picture":"https://techcrunch.com/wp-content/uploads/2019/08/Screen-Shot-2019-08-29-at-3.02.46-PM.png?w=1390&crop=1" }
];
prntfun(event){
console.log("###evnt detail####"+event.detail)
this.objdata[0].lastname=event.detail;
}
}
grandParent.html
<template>
<my-prnt onupdateme={gpfun}> ></my-prnt>
</template>
when you dispacth the event with bubbles:true and composed:true, you can use the same syntax as what you used in the parent component. Notice that onupdateme={gpfun}(Grand parent) and onupdateme={prntfun}(Parent) both are same in parent and grandparent.The only change is the function name, rest everything is same.
grandParent.js
import { LightningElement} from 'lwc';
export default class Gp extends LightningElement {
gpfun(){
console.log("#####Grand parent is called$$$$$$$");
}
}
Before clicking the button the output is as below.
Now after clicking "Update Prnt" , the Name of the Mark paul changes to Mark John, this updation is being done in the parent and passing back the data back to the child.
Even though we need not to use @track from the spring 20 release, there is one place that you need to use that is updating the fields of the objects. This example is the perfect suite of when you need to use @track. If you remove @track in the parent component child component will not reflect the name "John".
Below is the output which explains both child to parent and child to the grandparent. This approach will bubble up to the dom element until it reaches the first invocation of the dom hierarchy.
Notice Grand parent is called is basically coming from the grand parent. Initiation taking place from the child web component.
Thanks !
No comments:
Post a Comment