Bird
Raised Fist0
Svelteframework~10 mins

Component events (createEventDispatcher) in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Component events (createEventDispatcher)
Component A creates dispatcher
↓
Component A dispatches event
↓
Parent listens to event
↓
Parent handles event
↓
Parent updates state or reacts
Component A creates an event dispatcher, sends an event, and the parent listens and reacts to it.
Execution Sample
Svelte
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();

function sendMessage() {
  dispatch('message', { text: 'Hello from child' });
}
This code creates an event dispatcher and sends a 'message' event with data when sendMessage is called.
Execution Table
StepActionDispatcher StateEvent DispatchedParent ListenerParent Reaction
1Component initializesDispatcher createdNoneNo event yetNo reaction
2sendMessage() calledDispatcher readymessage event with {text: 'Hello from child'}Receives 'message' eventUpdates message display
3No further eventsDispatcher readyNoneNo eventNo change
💡 No more events dispatched, parent stops reacting.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
dispatchundefinedfunction createdfunction readyfunction ready
eventDataundefinedundefined{ text: 'Hello from child' }{ text: 'Hello from child' }
parentMessage'''''Hello from child''Hello from child'
Key Moments - 2 Insights
Why doesn't the parent react before the event is dispatched?
Because the parent listens for events dispatched by the child. Until dispatch('message') runs (see execution_table step 2), no event is sent, so no reaction happens.
What happens if dispatch is called with a different event name?
The parent only reacts if it listens for that specific event name. If the event name differs, the parent's listener won't catch it (see execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'parentMessage' after step 2?
A"" (empty string)
B"Hello from child"
Cundefined
Dnull
💡 Hint
Check variable_tracker row for 'parentMessage' after Step 2.
At which step does the parent receive the event?
AStep 1
BStep 3
CStep 2
DNo step
💡 Hint
Look at execution_table column 'Parent Listener' to see when event is received.
If the child dispatches an event named 'update' instead of 'message', what happens to the parent's reaction?
AParent does not react unless listening for 'update'
BParent reacts the same way
CParent throws an error
DParent reacts twice
💡 Hint
Refer to key_moments about event names and parent listeners.
Concept Snapshot
Use createEventDispatcher() in a Svelte child component to send events.
Call dispatch('eventName', data) to notify the parent.
Parent listens with on:eventName to react.
Events allow child-to-parent communication.
Event names must match for parent to catch them.
Full Transcript
In Svelte, components can send events to their parents using createEventDispatcher. First, the child component creates a dispatcher function. When an action happens, the child calls dispatch with an event name and optional data. The parent listens for this event by adding on:eventName to the child component tag. When the event fires, the parent runs its handler and can update its state or UI. This flow allows child components to communicate upwards without direct references. The event name must match between dispatch and the parent's listener. This example shows a child sending a 'message' event with text data, and the parent updating its display when it receives it.

Practice

(1/5)
1. What is the main purpose of createEventDispatcher in a Svelte component?
easy
A. To manage component state internally
B. To create a new component dynamically
C. To send custom events from a child component to its parent
D. To style components with CSS variables

Solution

  1. Step 1: Understand the role of createEventDispatcher

    This function is used to create a dispatcher that sends events from child to parent components.
  2. Step 2: Identify the correct purpose

    Among the options, only sending custom events matches the purpose of createEventDispatcher.
  3. Final Answer:

    To send custom events from a child component to its parent -> Option C
  4. Quick Check:

    createEventDispatcher sends events to parent [OK]
Hint: Remember: dispatch sends events upward to parent [OK]
Common Mistakes:
  • Confusing event dispatch with state management
  • Thinking it creates components
  • Assuming it styles components
2. Which of the following is the correct way to import and use createEventDispatcher in a Svelte component?
easy
A. import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher();
B. import createEventDispatcher from 'svelte'; const dispatch = createEventDispatcher();
C. import { createEventDispatcher } from 'svelte/internal'; const dispatch = createEventDispatcher();
D. import { dispatchEvent } from 'svelte'; const dispatch = dispatchEvent();

Solution

  1. Step 1: Check the import source

    The correct import is from 'svelte' using named import syntax.
  2. Step 2: Confirm usage

    Calling createEventDispatcher() returns the dispatch function to send events.
  3. Final Answer:

    import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); -> Option A
  4. Quick Check:

    Correct import and call syntax = import { createEventDispatcher } from 'svelte'; const dispatch = createEventDispatcher(); [OK]
Hint: Always import from 'svelte' with curly braces [OK]
Common Mistakes:
  • Importing from 'svelte/internal' which is private
  • Using default import instead of named import
  • Confusing dispatchEvent with createEventDispatcher
3. Given this Svelte child component code:
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();

function sendData() {
  dispatch('update', { value: 42 });
}

What will the parent component receive when listening with on:update?
medium
A. An event with event.detail containing { value: 42 }
B. An event with event.value equal to 42
C. A string 'update' without data
D. No event is sent because dispatch is not called

Solution

  1. Step 1: Understand dispatch call

    The dispatch function sends an event named 'update' with data inside an object as the second argument.
  2. Step 2: Recall event data access

    The parent receives the event and accesses data via event.detail, which holds the object { value: 42 }.
  3. Final Answer:

    An event with event.detail containing { value: 42 } -> Option A
  4. Quick Check:

    Data sent in event.detail = An event with event.detail containing { value: 42 } [OK]
Hint: Event data is always inside event.detail [OK]
Common Mistakes:
  • Expecting event.value instead of event.detail
  • Thinking dispatch sends only event name string
  • Assuming dispatch is not called
4. Identify the error in this Svelte child component code:
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher;

dispatch('click');
medium
A. dispatch cannot send events without a second argument
B. dispatch should be imported from 'svelte/internal'
C. dispatch must be called inside a function
D. Missing parentheses when calling createEventDispatcher

Solution

  1. Step 1: Check createEventDispatcher usage

    The code assigns dispatch to createEventDispatcher without calling it, missing parentheses.
  2. Step 2: Understand consequences

    Without calling createEventDispatcher(), dispatch is not a function, so dispatch('click') causes an error.
  3. Final Answer:

    Missing parentheses when calling createEventDispatcher -> Option D
  4. Quick Check:

    createEventDispatcher() must be called [OK]
Hint: Always call createEventDispatcher() with () [OK]
Common Mistakes:
  • Forgetting parentheses after createEventDispatcher
  • Importing from wrong module
  • Thinking second argument is mandatory
5. You want a child Svelte component to send two different events, save and cancel, each with different data. Which is the best way to implement this using createEventDispatcher?
hard
A. Create two dispatchers by calling createEventDispatcher() twice, one for each event
B. Create one dispatcher and call dispatch('save', data) or dispatch('cancel', data) as needed
C. Use dispatch('save_cancel', {saveData, cancelData}) to send both events at once
D. Send events by calling dispatchEvent directly on the DOM element

Solution

  1. Step 1: Understand dispatcher usage

    One dispatcher handles all custom events; you specify event names when calling dispatch.
  2. Step 2: Evaluate options

    Calling dispatch with different event names ('save' or 'cancel') is the correct pattern.
  3. Final Answer:

    Create one dispatcher and call dispatch('save', data) or dispatch('cancel', data) as needed -> Option B
  4. Quick Check:

    Single dispatcher handles multiple events [OK]
Hint: One dispatcher can send many event types by name [OK]
Common Mistakes:
  • Creating multiple dispatchers unnecessarily
  • Sending combined event instead of separate
  • Using DOM dispatchEvent instead of Svelte dispatch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard