0
0
Svelteframework~5 mins

Action with event dispatching in Svelte - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a Svelte action?
A Svelte action is a reusable function that can be applied to HTML elements to add behavior or side effects when the element is created or updated.
Click to reveal answer
intermediate
How do you dispatch a custom event from a Svelte action?
You create a new CustomEvent and use the element's dispatchEvent method to send it, allowing parent components to listen and react.
Click to reveal answer
intermediate
Why use event dispatching inside a Svelte action?
Event dispatching lets the action communicate with the component or other parts of the app, sending information like user interactions or state changes.
Click to reveal answer
advanced
Show the basic structure of a Svelte action that dispatches a 'custom' event.
function myAction(node) {
  const handleClick = () => {
    node.dispatchEvent(new CustomEvent('custom'));
  };
  node.addEventListener('click', handleClick);
  return {
    destroy() {
      node.removeEventListener('click', handleClick);
    }
  };
}
Click to reveal answer
beginner
How do you listen to a custom event dispatched by an action in a Svelte component?
Use the on:event syntax on the element where the action is applied, for example: <div use:myAction on:custom={handler}>.
Click to reveal answer
What parameter does a Svelte action function receive?
AThe component's props
BThe component instance
CThe event object
DThe HTML element node it is applied to
How do you remove event listeners in a Svelte action?
ABy returning a destroy function from the action
BBy calling removeEventListener outside the action
CBy using the onDestroy lifecycle function
DBy setting the event listener to null
Which method sends a custom event from an element in Svelte?
AdispatchEvent(new CustomEvent('eventName'))
Bemit('eventName')
Ctrigger('eventName')
DsendEvent('eventName')
How do you apply an action named 'myAction' to a div in Svelte?
A<div on:myAction></div>
B<div action={myAction}></div>
C<div use:myAction></div>
D<div bind:myAction></div>
What is the purpose of dispatching events from actions?
ATo style the element
BTo communicate from the action to the component
CTo fetch data from the server
DTo change the component's props directly
Explain how to create a Svelte action that dispatches a custom event when the user clicks the element.
Think about how to listen to clicks and send events from the element.
You got /4 concepts.
    Describe how a Svelte component listens to and handles a custom event dispatched by an action.
    Remember how events bubble and how Svelte binds event listeners.
    You got /3 concepts.