Member-only story
Passing Arguments into Svelte Actions
Svelte is an up and coming front end framework for developing front end web apps.
It’s simple to use and lets us create results fast.
In this article, we’ll look at how to pass parameters into actions.
Adding Parameters
Actions can take arguments. This means that the action will be called alongside the elements it belongs to.
For instance, we can create an app where we display a message when we clicked and held a button for a specified amount of time that we can change with a slider.
To make this, we write the following code:
longpress.js
export const longpress = (node, duration) => {
let timer; const handleMousedown = () => {
timer = setTimeout(() => {
node.dispatchEvent(new CustomEvent("longpress"));
}, duration);
}; const handleMouseup = () => {
clearTimeout(timer);
}; node.addEventListener("mousedown", handleMousedown);
node.addEventListener("mouseup", handleMouseup); return {
destroy() {
node.removeEventListener("mousedown", handleMousedown);
node.removeEventListener("mouseup", handleMouseup);
},
update(newDuration) {
duration = newDuration;
}
};
};
App.svelte
:
<script>
import { longpress } from "./longpress.js";let pressed = false;
let duration = 2000;
</script><label>
<input type=range bind:value={duration} max={2000} step={100}>
{duration}ms
</label><button use:longpress={duration}
on:longpress="{() => pressed = true}"
on:mouseenter="{() => pressed = false}"
>press and hold</button>{#if pressed}
<p>You pressed for {duration}ms</p>
{/if}
In the code above, we created a longpress
action that takes a duration
as an argument.
We have the update
method in the object we return to update the duration
when it’s passed in.
Then when we click the mouse, the mousedown
event is emitted, and then the handleMousedown
is called.