Consider this Svelte action that dispatches a custom event when the element is clicked.
function clickAction(node) {
const handleClick = () => {
node.dispatchEvent(new CustomEvent('customclick', { detail: { clicked: true } }));
};
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', handleClick);
}
};
}Which event name should you listen for in the component using this action?
Look at the event name passed to CustomEvent.
The action dispatches an event named customclick. You must listen for this exact event name.
Given this Svelte component using an action that dispatches an event:
<script>
let message = '';
function myAction(node) {
const sendEvent = () => {
node.dispatchEvent(new CustomEvent('notify', { detail: 'hello' }));
};
sendEvent();
return {};
}
</script>
<div use:myAction on:notify={e => message = e.detail}>Click me</div>
<p>{message}</p>What will be shown inside the <p> tag when the component renders?
The action dispatches the event immediately on mount.
The action dispatches 'notify' with detail 'hello' immediately, so the handler sets message to 'hello'.
Which of the following Svelte action implementations correctly dispatches a custom event named 'update' with detail { value: 42 } when the element is clicked?
Check that event listeners are properly added and removed, and that CustomEvent is used correctly.
Option A correctly adds and removes the event listener and dispatches a CustomEvent with the right syntax.
Given this Svelte action:
function action(node) {
node.addEventListener('click', () => {
node.dispatchEvent(new CustomEvent('change', { detail: 123 }));
});
return {};
}And this usage in a component:
<div use:action on:change={e => console.log(e.detail)}>Click me</div>Clicking the div does not log anything. Why?
Check if the custom event bubbles by default.
Custom events do not bubble by default. The handler on the node won't catch the event unless bubbles: true is set.
You want a Svelte action to dispatch a custom event that the component using the action can listen to with on:customEvent. Which approach ensures the event is properly received by the component?
Think about event propagation and where the component listens for events.
Dispatching the event on the node with bubbles: true allows the component to listen with on:customEvent on the element using the action.