1

I am trying to implement custom event handling function using salesforce lwc event handling. While dispatching event from child to parent , custom event handling function handleCustomEvent is not getting triggered by using this.template.addEventListener defined in constructor.

Child component html file like the following,

<template>
  <lightning-card title="Child Component">
    <div>
        <lightning-input name="textVal" label="Enter Text" onchange={handleChange}> 
        </lightning-input>
    </div>
 </lightning-card>
</template>

child .js file ,

export default class ChildCus extends LightningElement {

  handleChange(event) {
    event.preventDefault();
    const name = event.target.value;
    const selectEvent = new CustomEvent('mycustomevent', {
        detail: name,bubbles: true
    });
   this.dispatchEvent(selectEvent);
  }
}

Parent component html file,

<template>
  <div>
    Value From Child :  {msg}
    <c-child-comp ></c-child-comp>
  </div>
</template>

Parent component .js file,

export default class ParentCus extends LightningElement {

@track msg;
constructor() {
    super();   
   
    this.template.querySelector('c-child-comp').addEventListener(
        'mycustomevent',
        this.myCustomEventHandler
      );   
}
myCustomEventHandler = (event) => {
    this.handleCustomEvent(event);
  }
handleCustomEvent(event) {
    console.log("Test Point2");
    const textVal = event.detail;
    this.msg = textVal;
  
   }
}

UPDATE

according to answered suggestion , I am getting Uncaught SyntaxError: Unexpected token ':' (at childComp:1:10) in parent console and getting following screenshot while loading page,

enter image description here

In parent component js file, constructor is working without any error. But handleCustomEvent function is not getting triggered. Can anyone guide me to resolve this issue why its happening?

5
  • Any specific reason to not simply use onmycustomevent to bind a handler to that event on the child markup within the parent template?
    – Phil W
    Commented Feb 16, 2023 at 13:14
  • No reason. I am beginner in salesforce. So I am learning and practicing event handling by JavaScript using addEventListener method.
    – Mr.DevEng
    Commented Feb 16, 2023 at 13:29
  • 2
    Does this answer your question? LWC and addEventListener
    – Phil W
    Commented Feb 16, 2023 at 13:39
  • You might also want to check the documentation which shows using binding as an "anti-pattern" when using this.addEventListener and this.template.addEventListener.
    – Phil W
    Commented Feb 16, 2023 at 13:43
  • OK thank you. let me go through these.
    – Mr.DevEng
    Commented Feb 16, 2023 at 13:48

1 Answer 1

2
+50

You always want to attach the event listener to the source, not the destination. In other words, the thing that you want to listen to is the thing you should attach the method to. Note that the event handler cannot be added before the first time your component is rendered, so:

// ensures that "this" is correct by way of arrow function
#myCustomEventHandler = (event) => {
  this.handleCustomEvent(event);
}
renderedCallback() {
  this.template.querySelector('c-child-comp').addEventListener(
    'mycustomevent',
    this.#myCustomEventHandler
  );
}
disconnectedCallback() {
  // Make sure we avoid memory leaks
  this.template.querySelector('c-child-comp').removeEventListener(
    'mycustomevent',
    this.#myCustomEventHandler
  );
}

Note that the framework does automatically avoid duplicate handlers on the same event, so it's safe to not check if the event is already being listened for.

Demo.

2
  • according to answered suggestion , I am getting Uncaught SyntaxError: Unexpected token ':' (at childComp:1:10) in parent console. and getting the updated screenshot in question. Please check screnshot from edited question.
    – Mr.DevEng
    Commented Feb 20, 2023 at 7:30
  • @Mr.DevEng that's a syntax error in the child component, it appears. Makes sure the code is saved correctly. Also, try testing it in a Lighting App directly in Salesforce, see if that makes a difference.
    – sfdcfox
    Commented Feb 20, 2023 at 14:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .