I'm trying to wire in observedAttributes in web co...
# javascript
j
I'm trying to wire in observedAttributes in web components so that attributeChangedCallback would trigger when changing a property on the componenent The JavaScript implementation would be this and then the attributeChangedCallback should just work (for color and size in the case)
Copy code
class MyCustomElement extends HTMLElement {
  static observedAttributes = ["color", "size"];
https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements how would I define such a static variable in KotlinJs? My test-component:
Copy code
class BlahComponent :
    WebComponent.ConnectedCallback,
    WebComponent.DisconnectedCallback,
    WebComponent.AttributeChangedCallback,
    HTMLElement() {

    init {
        this.asDynamic().attachShadow(ShadowRootInit(ShadowRootMode.OPEN))
        this.asDynamic().shadowRoot.innerHTML = "<p>blah!!! </p>"
    }

    override fun connectedCallback() {
        println("connectedCallback")
        if (this.asDynamic().shadowRoot == null) {
            this.asDynamic().attachShadow(ShadowRootInit(ShadowRootMode.OPEN))
            this.asDynamic().shadowRoot.innerHTML = "<p>blah!!! </p>"
        }
    }

    override fun disconnectedCallback() {
        println("disconnectedCallback")
    }

    override fun attributeChangedCallback(name: String, oldValue: Any?, newValue: Any?) {
        println("attributeChangedCallback: $name $oldValue $newValue")
    }



    companion object {
        init {
            window.customElements.define("test-blah", BlahComponent::class.js as () -> dynamic)
        }
    }

}
So far I've tried:
Copy code
companion object {

        @JsStatic
        val observedAttributes = arrayOf("some-value")
Copy code
companion object {

        @JsStatic
        val observedAttributes 
            get() = arrayOf("some-value")
with and without the @JsStatic, I've tried adding @JsName in case the variable name gets obfuscated I've also tried using a function:
Copy code
companion object {
        
        @JsStatic
        @JsName("observedAttributes")
        fun observedAttributes() = arrayOf("some-value")
But none of these configurations triggers the attributeChangedCallback function. I've also tried adding the variable outside the companion object, but then @JsStatic doesn't compile and it probably has an even smaller chance of generating something static. Any ideas?
this hack seems to do the trick
Copy code
companion object {
    init {
        BlahComponent::class.js.asDynamic().observedAttributes = arrayOf("some-value")
        window.customElements.define("test-blah", BlahComponent::class.js as () -> dynamic)
    }
}
must be a more idiomatic KotlinJs way to do this
t
Please check it in production (
@JsStatic
)