0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-12-01 01:11:24 +01:00
svelte/documentation/tutorial/12-actions/02-adding-parameters-to-actions/text.md
Puru Vijay 993b40201c
feat(site-2): New Markdown renderer, FAQ, Blog, Tutorial, Docs, (#8603)
* New FAQ, new renderer

* Push blog stuff

* Fix blog posts

* Add tutorial to be rendered

* Update documentation/content/blog/2023-03-09-zero-config-type-safety.md

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>

* Update documentation/content/blog/2023-03-09-zero-config-type-safety.md

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>

* Revamp a lot of renderer, make it (soft) compatible with sveltekit

* Remove markdown types

* Clean up faq +page

* Document stuff

* Make the options more explicity

* chore(site-2): Restructure docs pt 2 (#8604)

* Push

* Update readme

* Push

* inor accessibility fix

* minr stuff

* Add prepare

* Run prettier

* Remove test script

* pnpm update

* Update sites/svelte.dev/src/routes/examples/[slug]/+page.svelte

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>

* Update sites/svelte.dev/package.json

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>

---------

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>

---------

Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
2023-05-25 18:19:38 +05:30

1.3 KiB

title
Adding parameters

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}}