Actions let you add custom behavior to HTML elements easily. Dispatching events from actions helps communicate changes back to the component.
Action with event dispatching in Svelte
function myAction(node) { const handle = () => { node.dispatchEvent(new CustomEvent('myEvent', { detail: { info: 'hello' } })); }; node.addEventListener('click', handle); return { destroy() { node.removeEventListener('click', handle); } }; }
The node parameter is the HTML element the action is applied to.
Use node.dispatchEvent to send custom events from the action.
function focusAction(node) { node.focus(); return { destroy() { // cleanup if needed } }; }
function clickNotify(node) { const onClick = () => { node.dispatchEvent(new CustomEvent('notify', { detail: { clicked: true } })); }; node.addEventListener('click', onClick); return { destroy() { node.removeEventListener('click', onClick); } }; }
This Svelte component uses an action called highlight that toggles a yellow background on the button when clicked. It also dispatches a custom event toggled with the current state. The component listens to this event and updates a message below the button.
<script> function highlight(node) { const handleClick = () => { node.classList.toggle('highlighted'); node.dispatchEvent(new CustomEvent('toggled', { detail: { highlighted: node.classList.contains('highlighted') } })); }; node.addEventListener('click', handleClick); return { destroy() { node.removeEventListener('click', handleClick); } }; } let message = 'Not highlighted'; function onToggled(event) { message = event.detail.highlighted ? 'Highlighted!' : 'Not highlighted'; } </script> <style> .highlighted { background-color: yellow; } button { padding: 0.5rem 1rem; font-size: 1rem; } </style> <button use:highlight on:toggled={onToggled} aria-pressed={message === 'Highlighted!'}> Click me </button> <p>{message}</p>
Always remove event listeners in the destroy method to avoid memory leaks.
Custom events can carry data in the detail property.
Use semantic HTML and ARIA attributes for accessibility, like aria-pressed on toggle buttons.
Actions add reusable behavior to elements.
Dispatch custom events from actions to communicate with components.
Clean up event listeners in the destroy method.
Practice
action in Svelte?Solution
Step 1: Understand what actions do
Actions in Svelte are functions that add behavior to elements, like event listeners or animations.Step 2: Compare options
Only To add reusable behavior to HTML elements correctly describes adding reusable behavior to elements, while others describe unrelated tasks.Final Answer:
To add reusable behavior to HTML elements -> Option BQuick Check:
Actions = reusable element behavior [OK]
- Confusing actions with components
- Thinking actions manage styles
- Assuming actions handle global state
notify from a Svelte action?Solution
Step 1: Recall how to dispatch events in Svelte actions
Custom events are dispatched usingnode.dispatchEvent(new CustomEvent('eventName')).Step 2: Check each option
node.dispatchEvent(new CustomEvent('notify')) matches the correct syntax. Others are either missingnew CustomEventor use invalid syntax.Final Answer:
node.dispatchEvent(new CustomEvent('notify')) -> Option DQuick Check:
Dispatch custom event = node.dispatchEvent(new CustomEvent()) [OK]
- Omitting 'new CustomEvent'
- Calling dispatchEvent without node
- Using incorrect method names
function clickAction(node) {
const handleClick = () => {
node.dispatchEvent(new CustomEvent('customClick', { detail: 'clicked' }));
};
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', handleClick);
}
};
}<button use:clickAction on:customClick={e => console.log(e.detail)}>Click me</button>Solution
Step 1: Understand the action's event dispatch
The action dispatches a 'customClick' event with detail 'clicked' when the button is clicked.Step 2: Check the event listener on the button
The button listens for 'customClick' and logs the event's detail, which is 'clicked'.Final Answer:
'clicked' will be logged to the console -> Option AQuick Check:
Custom event detail logged = 'clicked' [OK]
- Expecting default 'click' event detail
- Thinking event name must be 'click'
- Ignoring event detail property
function myAction(node) {
const onClick = () => {
node.dispatchEvent(CustomEvent('myEvent'));
};
node.addEventListener('click', onClick);
return {
destroy() {
node.removeEventListener('click', onClick);
}
};
}Solution
Step 1: Check how CustomEvent is created
The code callsCustomEvent('myEvent')without thenewkeyword, which is required to create an event instance.Step 2: Verify other parts
Event listener is correctly added and removed; destroy method exists; event names can be uppercase.Final Answer:
Missing 'new' keyword before CustomEvent -> Option CQuick Check:
CustomEvent requires 'new' keyword [OK]
- Forgetting 'new' before CustomEvent
- Removing event listener incorrectly
- Assuming event names must be lowercase
resize whenever the window is resized. Which of the following is the best way to implement this action?Solution
Step 1: Understand event source and dispatch
Window resize events come from the window object, so the listener must be added to window, not the node.Step 2: Implement dispatch and cleanup
The action should dispatch a custom 'resize' event from the node when window resizes, and remove the listener in destroy to avoid leaks.Final Answer:
Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy -> Option AQuick Check:
Listen on window, dispatch from node, cleanup in destroy [OK]
- Adding listener to node instead of window
- Not cleaning up event listener
- Dispatching event only once
Ready to prove it?
Pass the test and this pattern moves unknown
