6

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 '19 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 Mar 7 '19 at 12:56
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
});
| improve this answer | |
  • 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 Jul 31 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!

| improve this answer | |
  • 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 '19 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.