7

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.

2
  • do you have some markup or pseudo markup that shows the composition of the child and parent components?
    – pchittum
    Commented Mar 6, 2019 at 11:14
  • 1
    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
    Commented Mar 7, 2019 at 12:56

2 Answers 2

2

When you attach event listener programmatically, you need to explicitly set bubbles property to true, so that the event bubbles up to parent component.

Set 'bubbles : true' where you have declared your 'customEvent'.

Your code should be :

const selectEvent = new CustomEvent('select', {
    detail : this.contact.Id, bubbles : true
});
1
  • To add to this; if you programmatically add the listeners you are also responsible for programmatically unregistering them at the end of the component's life. Even then you may find some apparently strange issues because of the way LEX doesn't immediately destroy components when switching "record page" between multiple records of the same type. See this answer for details.
    – Phil W
    Commented Jul 31, 2020 at 15:53
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
  • 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.
    – nica
    Commented Mar 12, 2019 at 16:14

You must log in to answer this question.

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