Defining actions
Before we start to talk about using Svelte actions to create custom events, let’s quickly recap how to define an action in Svelte.
In Svelte, an action is nothing but a function that follows an action contract. This means if a function follows a specific function signature, it is considered an action. Here is the function signature of an action:
function action(node) { return { destroy() {} }; }
It is a function that optionally returns an object that has a destroy
method.
In this case, since the action
function follows the action contract, it is a Svelte action.
To use the Svelte action on an element, you can use the use:
directive:
<div use:action />
Here, we used the Svelte action named action
on the div
element.
So, what will happen to the div
element with a Svelte action?
When the <div>
element is mounted to the DOM, Svelte will call the action
function with the reference...