Discover how to make your components talk to each other effortlessly with Svelte actions!
Why Action with event dispatching in Svelte? - Purpose & Use Cases
Imagine you want to add a special effect to a button that tells the rest of your app when it's clicked, but you have to write extra code everywhere to listen and respond.
Manually adding event listeners and custom signals everywhere is messy, easy to forget, and makes your code hard to read and maintain.
Svelte's actions with event dispatching let you bundle behavior and communication in one place, so your components stay clean and talk to each other smoothly.
element.addEventListener('click', () => { customEvent(); });use:myAction on:customEvent={handleEvent}
function myAction(node) { const dispatch = name => node.dispatchEvent(new CustomEvent(name)); node.addEventListener('click', () => dispatch('customEvent')); }This lets you create reusable behaviors that send messages easily, making your app interactive and organized.
Think of a custom dropdown that tells its parent when an option is picked, without the parent needing to know the dropdown's inner details.
Manual event handling is repetitive and error-prone.
Actions with event dispatching bundle behavior and communication.
This keeps your Svelte components clean and interactive.
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
