Created
October 19, 2024 14:50
-
-
Save blinkinglight/da0bfdd56b85cac5773ae5a23b9d7f06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
class MyArray extends HTMLElement { | |
constructor() { | |
super(); | |
this.store = {}; | |
const template = document.createElement("template"); | |
const id = Math.random().toString(36).substr(2, 9); | |
template.innerHTML = `<div id="input-${id}">hi</div>`; | |
this.shadow = this.attachShadow({ mode: "open" }); | |
this.shadow.appendChild(template.content.cloneNode(true)); | |
this.input = this.shadow.getElementById("input-" + id); | |
this.initialized = false; | |
} | |
static get observedAttributes() { | |
return ['value']; | |
} | |
static get formAssociated() { return true; } | |
attributeChangedCallback(name, oldValue, newValue) { | |
this.store = newValue; | |
this.ar = JSON.parse(this.getAttribute("value")); | |
if (!this.initialized) { | |
this.initialized = true; | |
for (let k in this.ar) { | |
const lid = Math.random().toString(36).substr(2, 9); | |
const el = document.createElement(`input`); | |
el.setAttribute("id", `input-${lid}`); | |
el.setAttribute("type", "text"); | |
el.setAttribute("value", this.ar[k].Value); | |
const _this = this; | |
el.onkeyup = () => { | |
_this.ar[k].Value = el.value; | |
console.log('ar', _this.ar); | |
const ev = new CustomEvent("change", { detail: { ar: _this.ar } }) | |
this.dispatchEvent(ev); | |
}; | |
this.input.appendChild(el); | |
} | |
} | |
} | |
} | |
customElements.define('my-array', MyArray); | |
</script> | |
<div data-store="{ ar: [ { Key: 'kv1', Value: 'one'}, { Key: 'kv2', Value: 'Two'}]}"> | |
<my-array data-bind-value="$ar" data-on-change="$ar=event.detail.ar;console.log('asd', $ar)"></my-array> | |
</div> | |
<div data-text="JSON.stringify($ar)"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment