Performance: Event forwarding
Event forwarding affects interaction responsiveness and event handling efficiency in the browser.
/* Child.svelte */ <button on:click>Click me</button> /* Parent.svelte */ <Child on:click={handleChildClick} />
/* Child.svelte */ <script> import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); function handleClick(event) { dispatch('click', event); } </script> <button on:click={handleClick}>Click me</button> /* Parent.svelte */ <Child on:click={handleChildClick} />
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual event dispatch forwarding | Adds extra event listeners | 0 | 0 | [X] Bad |
| Native event forwarding (Svelte default) | No extra listeners | 0 | 0 | [OK] Good |
click event from a child component <Child /> to its parent in Svelte?on:eventName.<Child on:click />. Other options are invalid or unrelated.<!-- Parent.svelte -->
<Child on:customEvent={handleEvent} />
<script>
function handleEvent(e) {
console.log(e.detail);
}
</script>
<!-- Child.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function send() {
dispatch('customEvent', 'hello');
}
</script>
<button on:click={send}>Send</button>on:customEvent on the child and calls handleEvent, which logs e.detail.submit event?<!-- Parent.svelte -->
<Child on:submit={handleSubmit} />
<script>
function handleSubmit() {
alert('Submitted');
}
</script>
<!-- Child.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function submit() {
dispatch('submit');
}
</script>
<button on:click={submit}>Submit</button>on:submit may listen to the native event, not the child's custom event, causing confusion.Grandparent > Parent > Child. The Child dispatches a save event. How can you forward this event so the Grandparent can listen to it directly without adding handlers in Parent?save on Child and uses createEventDispatcher to dispatch the same event upward.Pass the test and this pattern moves unknown