Make state components update attributes on state change

This commit is contained in:
Talia 2023-12-23 21:16:07 +01:00
parent b46c5d1d5c
commit 64b73676cb
Signed by: darkwiiplayer
GPG key ID: 7808674088232B3E
2 changed files with 12 additions and 3 deletions

View file

@ -1,6 +1,6 @@
{
"name": "skooma",
"version": "1.4.1",
"version": "1.5.0",
"author": "darkwiiplayer",
"license": "Unlicense",
"main": "skooma.js",

View file

@ -203,8 +203,11 @@ export class StoredState extends State {
const attributeObserver = new MutationObserver(mutations => {
for (const {type, target, attributeName: name} of mutations) {
if (type == "attributes")
target.state.proxy[name] = target.getAttribute(name)
if (type == "attributes") {
const next = target.getAttribute(name)
if (target.state.proxy[name] !== next)
target.state.proxy[name] = next
}
}
})
@ -214,6 +217,12 @@ export const component = (generator, name) => {
constructor() {
super()
this.state = new State(Object.fromEntries([...this.attributes].map(attribute => [attribute.name, attribute.value])))
this.state.addEventListener("change", event => {
for (const [name, value] of event.changes) {
if (this.getAttribute(name) !== value)
this.setAttribute(name, value)
}
})
attributeObserver.observe(this, {attributes: true})
this.replaceChildren(generator(this.state))
}