emit
Using the emit method, you can actively trigger events, and these events follow a bubbling mechanism. This means the event bubbles from inner elements to outer ones, firing from the innermost to the outermost layer.
Here is an example demonstrating how to use the emit method to trigger a custom event and leverage the bubbling mechanism to pass the event to external elements:
-
I am target
-
-
In this example, we registered the same custom event handler custom-event for both the <ul> element and the <li> element. When we trigger the event using the emit method, the event bubbles from the <li> element to the <ul> element, activating both event handlers.
Custom Data
By including the data parameter, you can pass custom data to the event handler:
-
I am target
-
-
In this example, we pass custom data to the event handler via the data parameter. The event handler can retrieve the passed data through event.data.
Fire an event without bubbling
If you don’t want the event to bubble, you can pass bubbles: false when dispatching it.
-
I am target
-
-
In this example, we triggered a custom event using the bubbles: false parameter. This event will not bubble up to parent elements, so only the event handler of the <li> element is triggered.
Penetrating the Root Node
By default, events do not penetrate the shadow DOM of a custom component. However, you can make custom events penetrate the root node and trigger elements outside of it by setting composed: true.
{{loggerText}}
In this example, we create a custom element composed-test that contains an element inside its shadow DOM and a button that dispatches an event. By default, the event does not cross the shadow boundary to the root node. However, by setting composed: true when dispatching the event, we allow it to propagate through the shadow DOM and trigger elements outside the root node.