Consider this Svelte action that updates the background color of an element when the parameter changes:
function highlight(node, color) {
node.style.backgroundColor = color;
return {
update(newColor) {
node.style.backgroundColor = newColor;
},
destroy() {
node.style.backgroundColor = '';
}
};
}If this action is used on a <div> with initial color 'yellow' and later updated to 'lightblue', what will be the background color after update?
Think about what the update function does when called with a new parameter.
The update function runs when the parameter changes. It sets the background color to the new value, so after update, the color is 'lightblue'.
Given a Svelte action with a destroy method, when does Svelte call this method?
Think about cleanup tasks and when they should happen.
The destroy method is called when the element using the action is removed from the DOM, allowing cleanup like removing event listeners.
Choose the correct Svelte action syntax that includes both update and destroy methods.
Remember the action must return an object with methods.
Option A correctly returns an object with update and destroy methods. Other options have syntax errors or missing return.
Look at this action:
function example(node, param) {
console.log('init', param);
return {
update(newParam) {
console.log('update', newParam);
}
};
}When the parameter changes, the 'update' log never appears. What is the likely cause?
Think about how Svelte knows to call update.
The update method runs only if the action is used with a reactive parameter that changes. If the action is not re-applied with a new parameter, update won't run.
Consider this Svelte action and usage:
function textAction(node, text) {
node.textContent = text;
return {
update(newText) {
node.textContent = newText;
},
destroy() {
node.textContent = 'Removed';
}
};
}
// Usage in a component:
// <div use:textAction={message}></div>
// Initial message = 'Hello'
// Then message changes to 'World'
// Then the div is removed from DOM
What is the text content of the div at each stage?
Remember what update and destroy do to the text content.
The action sets textContent to 'Hello' initially, updates it to 'World' when message changes, and sets it to 'Removed' when the element is removed.