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.
Those are internals which can break at any point, so I would not recommend that.
\nYou 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>-
|
I updated the global HTMLAttributes interface to add a property like so => declare global {
namespace svelteHTML {
interface HTMLAttributes<T> {
test?: () => void;
}
}
}Now I was hoping to access and read this like element.test after getting a reference to the element, but element.test is undefined; |
Beta Was this translation helpful? Give feedback.
-
|
If you set an unknown attribute/property, Svelte will compile that to just setting an attribute on the element, so there is no supported way of doing that. I also would not recommend it; mixing standardized attributes with arbitrary custom properties is likely to just cause confusion. I would probably use an attachment and a <script>
import { fn } from './fn.js';
let div;
$effect(() => {
fn.for(div)();
});
</script>
<div
bind:this={div}
{@attach fn(() => console.log('Attached function called'))}>
An element
</div>// fn.js
const map = new Map();
export const fn = value => node => {
map.set(node, value);
return () => map.delete(node);
};
fn.for = node => map.get(node); |
Beta Was this translation helpful? Give feedback.
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: