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.
select
event should bebubble
andcomposed
to reach the parent:new CustomEvent('select', { detail, bubbles: true, composed: true })
. Make sure to add the event listener in yourconnectedCallback
instead of yourconstructor
.