A Svelte action is a reusable function that can be applied to HTML elements to add behavior or side effects when the element is created or updated.
Click to reveal answer
intermediate
How do you dispatch a custom event from a Svelte action?
You create a new CustomEvent and use the element's dispatchEvent method to send it, allowing parent components to listen and react.
Click to reveal answer
intermediate
Why use event dispatching inside a Svelte action?
Event dispatching lets the action communicate with the component or other parts of the app, sending information like user interactions or state changes.
Click to reveal answer
advanced
Show the basic structure of a Svelte action that dispatches a 'custom' event.
The code calls CustomEvent('myEvent') without the new keyword, 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 C
Quick Check:
CustomEvent requires 'new' keyword [OK]
Hint: Always use 'new CustomEvent' to create events [OK]
Common Mistakes:
Forgetting 'new' before CustomEvent
Removing event listener incorrectly
Assuming event names must be lowercase
5. You want to create a Svelte action that dispatches a custom event resize whenever the window is resized. Which of the following is the best way to implement this action?
hard
A. Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy
B. Add a 'resize' listener to the node element directly and dispatch event from node
C. Dispatch 'resize' event once when the action is initialized
D. Use a setInterval to check window size and dispatch event repeatedly
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 A
Quick Check:
Listen on window, dispatch from node, cleanup in destroy [OK]
Hint: Listen on window, dispatch from node, cleanup in destroy [OK]
Common Mistakes:
Adding listener to node instead of window
Not cleaning up event listener
Dispatching event only once
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.