Skip to content
\n

Now I was hoping to access and read this like element.test after getting a reference to the element, but element.test is undefined;
\nThere is an element.__attributes which has the \"test\" property inside of it, but I'm not sure if it's a good Idea to use this. What should I do instead? I want to be able to read objects and functions, not just strings, like you would normally do with data-attributes.

","upvoteCount":1,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"

Those are internals which can break at any point, so I would not recommend that.

\n

You could write the attachment in such a way that you can just add arbitrary objects, though you will have to manually supply types in that case (e.g. in a factory function), the usage would look something like:

\n
<script lang=\"ts\">\n\timport { createPropsAttachments } from './element-attachments.js';\n\n\tlet div;\n\n\t// can also be extracted to a module for sharing\n\tconst attachProps = createPropsAttachments<{ a: number, b: string }>();\n\n\t$effect(() => {\n\t\tconst { a, b } = attachProps.for(div);\n\t});\n</script>\n\n<div\n\tbind:this={div}\n\t{@attach attachProps({ a: 1, b: '2' })}>\n\tAn element\n</div>
","upvoteCount":0,"url":"https://github.com/sveltejs/svelte/discussions/16706#discussioncomment-14306563"}}}
Discussion options

You must be logged in to vote

Those are internals which can break at any point, so I would not recommend that.

You could write the attachment in such a way that you can just add arbitrary objects, though you will have to manually supply types in that case (e.g. in a factory function), the usage would look something like:

<script lang="ts">
	import { createPropsAttachments } from './element-attachments.js';

	let div;

	// can also be extracted to a module for sharing
	const attachProps = createPropsAttachments<{ a: number, b: string }>();

	$effect(() => {
		const { a, b } = attachProps.for(div);
	});
</script>

<div
	bind:this={div}
	{@attach attachProps({ a: 1, b: '2' })}>
	An element
</div>

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@HighFunctioningSociopathSH
Comment options

@brunnerh
Comment options

Answer selected by HighFunctioningSociopathSH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants