Actions /
Adding parameters
a. Basics b. Adding data c. Dynamic attributes d. Styling e. Nested components f. Making an app a. Assignments b. Declarations c. Statements d. Updating arrays and objects a. Declaring props b. Default values c. Spread props a. If blocks b. Else blocks c. Else-if blocks d. Each blocks e. Keyed each blocks f. Await blocks a. DOM events b. Inline handlers c. Event modifiers d. Component events e. Event forwarding f. DOM event forwarding a. Text inputs b. Numeric inputs c. Checkbox inputs d. Group inputs e. Textarea inputs f. Select bindings g. Select multiple h. Contenteditable bindings i. Each block bindings j. Media elements k. Dimensions l. This m. Component bindings n. Binding to component instances a. onMount b. onDestroy c. beforeUpdate and afterUpdate d. tick a. Writable stores b. Auto-subscriptions c. Readable stores d. Derived stores e. Custom stores f. Store bindings a. Tweened b. Spring a. The transition directive b. Adding parameters c. In and out d. Custom CSS transitions e. Custom JS transitions f. Transition events g. Local transitions h. Deferred transitions i. Key blocks a. The animate directive a. The use directive b. Adding parameters a. The class directive b. Shorthand class directive c. Inline styles d. The style directive a. Slots b. Slot fallbacks c. Named slots d. Checking for slot content e. Slot props a. setContext and getContext a. <svelte:self> b. <svelte:component> c. <svelte:element> d. <svelte:window> e. <svelte:window> bindings f. <svelte:document> g. <svelte:body> h. <svelte:head> i. <svelte:options> j. <svelte:fragment> a. Sharing code b. Exports a. The @debug tag b. HTML tags a. Congratulations!
Like transitions and animations, an action can take an argument, which the action function will be called with alongside the element it belongs to.
Here, we're using a longpress
action that fires an event with the same name whenever the user presses and holds the button for a given duration. Right now, if you switch over to the longpress.js
file, you'll see it's hardcoded to 500ms.
We can change the action function to accept a duration
as a second argument, and pass that duration
to the setTimeout
call:
export function longpress (node , duration) {
// ...
const handleMousedown = () => {
timer = setTimeout (() => {
node .dispatchEvent (
new CustomEvent ( 'longpress' )
);
} , duration);
};
// ...
}
Back in App.svelte
, we can pass the duration
value to the action:
< button use :longpress = {duration}
This almost works — the event now only fires after 2 seconds. But if you slide the duration down, it will still take two seconds.
To change that, we can add an update
method in longpress.js
. This will be called whenever the argument changes:
return {
update (newDuration) {
duration = newDuration;
} ,
// ...
};
If you need to pass multiple arguments to an action, combine them into a single object, as in use:longpress={{duration, spiciness}}
Show me