4

Has anyone been able to attach event listener programmatically?

I defined handleClick function in child component as follows:

handleClick(event) {
    event.preventDefault();
    const selectEvent = new CustomEvent('select', {
        detail: this.contact.Id
    });
    this.dispatchEvent(selectEvent);
}

This is the JS file of parent component:

constructor() {
    super();
    this.template.addEventListener('select', this.handleSelect.bind(this));
  }

handleSelect(event) {
    console.log(event.detail);
}

handleSelect method is never called. Seems like the listener is not attached during the instantiating time. But this code works when the event listener is attached declaratively.

  • do you have some markup or pseudo markup that shows the composition of the child and parent components? – pchittum Mar 6 at 11:14
  • The select event should be bubble and composed to reach the parent: new CustomEvent('select', { detail, bubbles: true, composed: true }). Make sure to add the event listener in your connectedCallback instead of your constructor. – pmdartus Mar 7 at 12:56
0

The documentation says it follows the HTML spec on Templates for the constructor, which says you can use the constructor to add event listeners. However, perhaps there is a reason the documentation later goes on to show adding event listeners in the constructedCallback() portion of the lifecycle.

https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_lifecycle_hooks_dom

You could try that!

  • 1
    This example illustrates importing pubsub module, and then calling the JS functions. This is different, this is something like having 2 components in a separate containers and then having communication with them, there is no parent child hierarchy. – snl Mar 12 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.