destroy method. What is the purpose of this method in the action's lifecycle?function highlight(node) { node.style.backgroundColor = 'yellow'; return { destroy() { node.style.backgroundColor = ''; } }; }
The destroy method in a Svelte action is called automatically when the element using the action is removed from the DOM. This allows the action to clean up any changes or event listeners it added, preventing memory leaks or unwanted side effects.
<p> element after the component mounts?function setText(node) { node.textContent = 'Hello from action!'; } /* Usage in component: */ // <p use:setText></p>
The action setText sets the textContent of the element it is applied to. When the component mounts, the paragraph's text will be replaced with 'Hello from action!'.
Option C correctly defines an update method that receives the new parameter and updates the element's color style. Option C incorrectly attaches update to the node instead of returning it. Option C's update method ignores the new parameter. Option C updates backgroundColor instead of color.
function focusAction(node) { node.focus(); return { destroy() { node.blur(); } }; } // Usage: <input use:focusAction />
The destroy method runs when the element is removed. Calling node.blur() on a detached element can cause a runtime error because the element is no longer in the document. This is why option B is correct.
Svelte actions let you write reusable code that directly manipulates elements and handles setup and cleanup. This means you can add the same behavior to many elements easily without repeating code. They do not create new components or replace event handlers globally.