When building with HTML, the standard way to define properties/data on an element is through HTML attributes:
<img src="https://example.tld/image.png" alt="An Image" />
Here, src and alt are set on an <img> tag to provide data describing how
to render the image. Changing either of those attributes cause the image
(or alt text) to update. This can be considered a "reactive attribute," since
something on the page changes with the value.
Since Palette Components are standard HTML elements, they can use attributes just as any other tag would.
By default, attributes are not reactive. Changing an attribute on a Palette component will do nothing unless you have specified reactive behaviors for it.
<example-component content="Hello, world!"></example-component>
define("example-component", {
template = html`
<span>${"@content"}</span>
`
});
This component will display Hello, world! inside of a <span> tag, but if you
change the content attribute on the root element, the template will not
update automatically. This is because Palette has not been instructed to care
about changes to this attribute.
To specify that an attribute should cause a re-render, you can define it in the
observedAttributes property on your component:
define("example-component", {
observedAttributes: ["content"],
template = html`
<span>${"@content"}</span>
`
});
If you need more advanced functionality for live attributes, you can use the
beforeUpdate() and afterUpdate() hooks to monitor changes to observed
attributes:
define("user-profile", {
observedAttributes: ["username"],
beforeUpdate(changedAttrs: Record<string, string | null>) {
/* act on changed values */
}
afterUpdate(previousAttrs: Record<string, string | null>) {
/* modify own attribues as needed */
}
});
You can safely set observed attributes in beforeUpdate() and afterUpdate()
without triggering another render cycle. Palette ignores attribute changes
during the render.