Skip to main content

svelte/attachments

import { import createAttachmentKeycreateAttachmentKey, import fromActionfromAction } from 'svelte/attachments';

createAttachmentKey

Available since 5.29

Creates an object key that will be recognised as an attachment when the object is spread onto an element, as a programmatic alternative to using {@attach ...}. This can be useful for library authors, though is generally not needed when building an app.

<script>
	import { createAttachmentKey } from 'svelte/attachments';

	const props = {
		class: 'cool',
		onclick: () => alert('clicked'),
		[createAttachmentKey()]: (node) => {
			node.textContent = 'attached!';
		}
	};
</script>

<button {...props}>click me</button>
function createAttachmentKey(): symbol;

fromAction

function fromAction<
	Node extends HTMLElement,
	Parameter extends any
>(
	...args: undefined extends NoInfer<Parameter>
		? [
				action: (
					node: Node,
					parameter?: never
				) => void | ActionReturn<
					Parameter,
					Record<never, any>
				>,
				parameter?: (() => NoInfer<Parameter>) | undefined
			]
		: [
				action: (
					node: Node,
					parameter: Parameter
				) => void | ActionReturn<
					Parameter,
					Record<never, any>
				>,
				parameter: () => NoInfer<Parameter>
			]
): Attachment<Node>;

Attachment

An attachment is a function that runs when an element is mounted to the DOM, and optionally returns a function that is called when the element is later removed.

It can be attached to an element with an {@attach ...} tag, or by spreading an object containing a property created with createAttachmentKey.

interface Attachment<T extends EventTarget = Element> {}
(element: T): void | (() => void);

FromAction

interface FromAction<
	Element extends EventTarget = HTMLElement,
	Par = unknown
> {}
<Node extends Element, Parameter extends Par>(
	...args: undefined extends NoInfer<Parameter>
		? [
				action: (node: Node, parameter?: never) => void | ActionReturn<Parameter>,
				parameter?: () => NoInfer<Parameter>
			]
		: [
				action: (node: Node, parameter: Parameter) => void | ActionReturn<Parameter>,
				parameter: () => NoInfer<Parameter>
			]
): Attachment<Node>;

Edit this page on GitHub llms.txt