Performance: Action with event dispatching
This affects interaction responsiveness and event handling efficiency in the browser.
function myAction(node) { const handleClick = () => { node.dispatchEvent(new CustomEvent('myEvent', { detail: { clicked: true } })); }; node.addEventListener('click', handleClick); return { destroy() { node.removeEventListener('click', handleClick); } }; }
function myAction(node) { node.addEventListener('click', () => { node.dispatchEvent(new CustomEvent('myEvent', { detail: { clicked: true } })); }); return { destroy() { node.removeEventListener('click', () => {}); } }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Anonymous event listener in action | No extra DOM nodes | 0 reflows | Minimal paint | [X] Bad |
| Named event listener with proper cleanup | No extra DOM nodes | 0 reflows | Minimal paint | [OK] Good |
action in Svelte?notify from a Svelte action?node.dispatchEvent(new CustomEvent('eventName')).new CustomEvent or use invalid syntax.function clickAction(node) {
const handleClick = () => {
node.dispatchEvent(new CustomEvent('customClick', { detail: 'clicked' }));
};
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', handleClick);
}
};
}<button use:clickAction on:customClick={e => console.log(e.detail)}>Click me</button>function myAction(node) {
const onClick = () => {
node.dispatchEvent(CustomEvent('myEvent'));
};
node.addEventListener('click', onClick);
return {
destroy() {
node.removeEventListener('click', onClick);
}
};
}CustomEvent('myEvent') without the new keyword, which is required to create an event instance.resize whenever the window is resized. Which of the following is the best way to implement this action?Pass the test and this pattern moves unknown