Consider a Svelte component using a named action with a parameter. What is the behavior when the parameter changes?
<script> let color = 'red'; function highlight(node, params) { node.style.backgroundColor = params.color; return { update(newParams) { node.style.backgroundColor = newParams.color; }, destroy() { node.style.backgroundColor = null; } }; } </script> <button use:highlight={{ color }} on:click={() => color = color === 'red' ? 'blue' : 'red'}>Toggle Color</button>
Think about what the update method inside the action does when parameters change.
The named action's update method runs whenever the parameter changes. It updates the node's background color accordingly, so clicking toggles the color between red and blue.
Identify the correct syntax for a named action that cleans up by removing an event listener when destroyed.
Check the syntax of the destroy method and the parameters passed to removeEventListener.
Option C correctly defines the destroy method with parentheses and removes the exact event listener by passing both the event type and handler function.
Given the following named action, why does the background color not update when the parameter changes?
function highlight(node, params) { node.style.backgroundColor = params.color; return { destroy() { node.style.backgroundColor = null; } }; } // Used as: <div use:highlight={{ color }}></div>
Think about how Svelte named actions handle parameter changes.
Named actions must provide an update method to react to parameter changes. Without it, the action only runs once on mount.
Consider this Svelte component using a named action that updates text content based on a parameter. What is the final text shown after clicking the button twice?
<script> let label = 'Hello'; function updateText(node, params) { node.textContent = params.text; return { update(newParams) { node.textContent = newParams.text; } }; } </script> <button use:updateText={{ text: label }} on:click={() => label = label === 'Hello' ? 'World' : 'Hello'}>Toggle</button>
Each click toggles the label. After two clicks, what is the label value?
The label toggles: 'Hello' → 'World' → 'Hello'. After two clicks, the text content is 'Hello'.
Choose the statement that correctly explains the lifecycle methods and their order in a Svelte named action.
Recall the order of lifecycle methods: mount, update, destroy.
The named action function runs when the element mounts. The update method runs whenever parameters change. The destroy method runs when the element unmounts.