Bird
Raised Fist0
Svelteframework~10 mins

Action with event dispatching in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Action with event dispatching
Component mounts
↓
Action initialized
↓
User event triggers action
↓
Action dispatches custom event
↓
Component listens and handles event
↓
Component updates state/UI
This flow shows how a Svelte action attaches to an element, listens for user events, dispatches a custom event, and the component reacts to update UI.
Execution Sample
Svelte
function myAction(node) {
  const handleClick = () => {
    node.dispatchEvent(new CustomEvent('myEvent'));
  };
  node.addEventListener('click', handleClick);
  return { destroy() { node.removeEventListener('click', handleClick); } };
}
This Svelte action listens for clicks on an element and dispatches a custom event 'myEvent' when clicked.
Execution Table
StepActionEvent Listener AddedEvent TriggeredCustom Event DispatchedComponent Reaction
1Component mounts and action attachesclick listener added to nodeNoNoNo
2User clicks elementclick listener activeYesYes: 'myEvent'Component catches 'myEvent'
3Component updates state/UI based on eventlistener still activeNoNoUI updates accordingly
4Component unmounts or action removedclick listener removedNoNoNo further reactions
💡 Action cleans up event listener when component unmounts or action is destroyed
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
nodeDOM element referenceListener attachedListener activeListener activeListener removed
handleClickFunction definedRegistered as listenerCalled on clickNot calledRemoved
Key Moments - 2 Insights
Why does the custom event 'myEvent' need to be dispatched inside the action?
Because the action controls the element's behavior and dispatching the event inside it lets the component listen and react to user interactions, as shown in execution_table step 2.
What happens if the event listener is not removed when the component unmounts?
The listener stays active causing potential memory leaks or unexpected behavior. Execution_table step 4 shows the cleanup removing the listener.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the custom event 'myEvent' dispatched?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Custom Event Dispatched' column in execution_table
According to variable_tracker, what happens to the 'handleClick' function after step 4?
AIt is called repeatedly
BIt is removed as listener
CIt remains registered as listener
DIt dispatches more events
💡 Hint
Look at the 'handleClick' row under 'Final' column in variable_tracker
If the user never clicks the element, which steps in execution_table will occur?
ASteps 1 and 4 only
BSteps 1, 2, and 3
CAll steps
DOnly step 2
💡 Hint
Refer to 'Event Triggered' column to see when user clicks happen
Concept Snapshot
Svelte actions attach behavior to elements.
They can listen for events and dispatch custom events.
Components listen to these custom events to update UI.
Always clean up event listeners in action's destroy.
Use node.dispatchEvent(new CustomEvent('name')) inside action.
Full Transcript
In Svelte, an action is a function that attaches to a DOM element when the component mounts. This action can add event listeners to the element, such as listening for clicks. When the user clicks the element, the action dispatches a custom event using node.dispatchEvent with a CustomEvent. The component listens for this custom event and updates its state or UI accordingly. When the component unmounts or the action is removed, the event listener is cleaned up to avoid memory leaks. This flow ensures interactive behavior is encapsulated in the action and the component reacts to events cleanly.

Practice

(1/5)
1. What is the main purpose of an action in Svelte?
easy
A. To create new components
B. To add reusable behavior to HTML elements
C. To style elements with CSS
D. To manage global state

Solution

  1. Step 1: Understand what actions do

    Actions in Svelte are functions that add behavior to elements, like event listeners or animations.
  2. Step 2: Compare options

    Only To add reusable behavior to HTML elements correctly describes adding reusable behavior to elements, while others describe unrelated tasks.
  3. Final Answer:

    To add reusable behavior to HTML elements -> Option B
  4. Quick Check:

    Actions = reusable element behavior [OK]
Hint: Actions add behavior to elements, not create components [OK]
Common Mistakes:
  • Confusing actions with components
  • Thinking actions manage styles
  • Assuming actions handle global state
2. Which of the following is the correct way to dispatch a custom event named notify from a Svelte action?
easy
A. new Event('notify').dispatch(node)
B. dispatch('notify')
C. dispatchEvent('notify')
D. node.dispatchEvent(new CustomEvent('notify'))

Solution

  1. Step 1: Recall how to dispatch events in Svelte actions

    Custom events are dispatched using node.dispatchEvent(new CustomEvent('eventName')).
  2. Step 2: Check each option

    node.dispatchEvent(new CustomEvent('notify')) matches the correct syntax. Others are either missing new CustomEvent or use invalid syntax.
  3. Final Answer:

    node.dispatchEvent(new CustomEvent('notify')) -> Option D
  4. Quick Check:

    Dispatch custom event = node.dispatchEvent(new CustomEvent()) [OK]
Hint: Use node.dispatchEvent with new CustomEvent('name') [OK]
Common Mistakes:
  • Omitting 'new CustomEvent'
  • Calling dispatchEvent without node
  • Using incorrect method names
3. Given this Svelte action code, what will be logged when the button is clicked?
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>
medium
A. 'clicked' will be logged to the console
B. Nothing will be logged
C. An error will occur because 'customClick' is invalid
D. 'click' will be logged instead of 'clicked'

Solution

  1. Step 1: Understand the action's event dispatch

    The action dispatches a 'customClick' event with detail 'clicked' when the button is clicked.
  2. Step 2: Check the event listener on the button

    The button listens for 'customClick' and logs the event's detail, which is 'clicked'.
  3. Final Answer:

    'clicked' will be logged to the console -> Option A
  4. Quick Check:

    Custom event detail logged = 'clicked' [OK]
Hint: Custom event detail is logged on event listener [OK]
Common Mistakes:
  • Expecting default 'click' event detail
  • Thinking event name must be 'click'
  • Ignoring event detail property
4. Identify the error in this Svelte action code that dispatches a custom event:
function myAction(node) {
  const onClick = () => {
    node.dispatchEvent(CustomEvent('myEvent'));
  };
  node.addEventListener('click', onClick);
  return {
    destroy() {
      node.removeEventListener('click', onClick);
    }
  };
}
medium
A. destroy method is missing
B. Event listener is added to the wrong node
C. Missing 'new' keyword before CustomEvent
D. Custom event name must be lowercase

Solution

  1. Step 1: Check how CustomEvent is created

    The code calls CustomEvent('myEvent') without the new keyword, which is required to create an event instance.
  2. Step 2: Verify other parts

    Event listener is correctly added and removed; destroy method exists; event names can be uppercase.
  3. Final Answer:

    Missing 'new' keyword before CustomEvent -> Option C
  4. Quick Check:

    CustomEvent requires 'new' keyword [OK]
Hint: Always use 'new CustomEvent' to create events [OK]
Common Mistakes:
  • Forgetting 'new' before CustomEvent
  • Removing event listener incorrectly
  • Assuming event names must be lowercase
5. You want to create a Svelte action that dispatches a custom event resize whenever the window is resized. Which of the following is the best way to implement this action?
hard
A. Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy
B. Add a 'resize' listener to the node element directly and dispatch event from node
C. Dispatch 'resize' event once when the action is initialized
D. Use a setInterval to check window size and dispatch event repeatedly

Solution

  1. Step 1: Understand event source and dispatch

    Window resize events come from the window object, so the listener must be added to window, not the node.
  2. Step 2: Implement dispatch and cleanup

    The action should dispatch a custom 'resize' event from the node when window resizes, and remove the listener in destroy to avoid leaks.
  3. Final Answer:

    Add a window 'resize' listener inside the action, dispatch 'resize' event from the node, and clean up in destroy -> Option A
  4. Quick Check:

    Listen on window, dispatch from node, cleanup in destroy [OK]
Hint: Listen on window, dispatch from node, cleanup in destroy [OK]
Common Mistakes:
  • Adding listener to node instead of window
  • Not cleaning up event listener
  • Dispatching event only once
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