Performance: Action update and destroy
This concept affects how efficiently DOM elements are updated and cleaned up, impacting interaction responsiveness and memory usage.
function myAction(node, params) { function handleClick() { console.log('clicked with', params); } node.addEventListener('click', handleClick); return { update(newParams) { params = newParams; }, destroy() { node.removeEventListener('click', handleClick); } }; }
function myAction(node) { node.addEventListener('click', () => console.log('clicked')); return { update(newParams) { // no cleanup of old listeners node.addEventListener('click', () => console.log('clicked with', newParams)); }, // no destroy method }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Adding new listeners on every update | Multiple event listeners added | No direct reflows but slows event handling | Minimal paint cost | [X] Bad |
| Single listener with update and destroy cleanup | One event listener reused | No reflows triggered | Minimal paint cost | [OK] Good |
destroy function in a Svelte action?destroy in Svelte actionsdestroy function is called when the element using the action is removed from the DOM to clean up any side effects or event listeners.update handles parameter changes, and initialization happens in the main action function, not in destroy.update and destroy function from a Svelte action?update and destroy methods as properties.update and destroy as arrow functions. Other options use invalid syntax or wrong property names.function highlight(node, color) {
node.style.backgroundColor = color;
return {
update(newColor) {
node.style.backgroundColor = newColor;
},
destroy() {
node.style.backgroundColor = '';
}
};
}update method runs when the action's parameter changes, here it sets the background color to the new value.update, which sets node.style.backgroundColor to 'lightblue'.function logClicks(node) {
function handleClick() {
console.log('Clicked');
}
node.addEventListener('click', handleClick);
return {
update() {
node.removeEventListener('click', handleClick);
}
};
}destroy method to remove the listener on element removal, which can cause memory leaks.update and destroy?update method should take a newColor parameter and set node.style.color = newColor.destroy method should console.log('Element removed').Pass the test and this pattern moves unknown