Event Propagation in LWC

Updated: Jun 28, 2020

In previous blog, the event handler was declarative in parent component. There is one more way to handle a custom event.

Handle a Custom Event Programmatically - Use following statement to declare an event handler in constructor. where 'eventname' is the name of custom event, and 'handlerFunction' is the event handler method.

Declare Event Handler -

this.template.addEventListener('eventname', this.handlerFunction.bind(this));

Dispatch Event -

this.dispatchEvent(new CustomEvent('btnclick', { bubbles: true , composed : true }));

Above statement is dispatching a custom event. The second part of the statement is { bubbles: true , composed : true }, which is used for event propagation. While defining handler using programmatic statement, If we omit this statement the event would not cross the child component boundary, and event handler would not be called. When we create an event, bubbles and composed define the event propagation behavior.

bubbles - Define whether event bubble up the DOM or not.