is there a way to force a constructor call in Kotl...
# javascript
j
is there a way to force a constructor call in KotlinJs or to initialize all local variables automatically? currently my init / super aren't being called when using web components and neither are local variables initialized Temp workaround seems to be to initialize values inside the connectedCallback which is not great, otherwise all that renders is
Test: counter = undefined undefined 9000
Copy code
class Test :
    WebComponent.ConnectedCallback,
    HTMLElement() {

    private var varCounter = 1234
    private var valCounter = 5678

    init {
        this.asDynamic().attachShadow(ShadowRootInit(ShadowRootMode.OPEN))
        render()
    }

    override fun connectedCallback() {
        // hacky workaround since init is not called
        if (this.asDynamic().shadowRoot == null) {
            this.asDynamic().attachShadow(ShadowRootInit(ShadowRootMode.OPEN))
            varCounter = 1234  // hacky workaround since local var is not initialized
            valCounter = 5678  // hacky workarond since local val is not initialized

        }
        render()
    }

    fun render() {
        this.asDynamic().shadowRoot.innerHTML = "Test: counter = $varCounter $valCounter $constCounter"
    }

    companion object {
        init {
            Test::class.js.register("test-test")
        }

        private const val constCounter = 9000
    }

}
rest of the code to run this: https://youtrack.jetbrains.com/issue/KT-60651/KJS-ES6-init-block-and-constructor-are-not-called#focus=Comments-27-11838522.0-0
t
AFAIK It should work fine in production
j
Mmm, it does indeed, but only if I annotate the class
Copy code
@JsExport
otherwise the class name gets minified to
st
or something else so that means I'll need to dev using
Copy code
./gradlew :demo:jsBrowserProductionRun --continuous
instead of
Copy code
/gradlew :demo:jsBrowserDevelopmentRun --continuous
even the attachShadow onConnectedCallback hack I can remove when running in Prod mode final working class:
Copy code
@JsExport
class Test :
    WebComponent.AttributeChangedCallback,
    HTMLElement() {

    private var varCounter = 1234
    private val valCounter = 5678
    private var test: String = ""

    init {
        this.asDynamic().attachShadow(ShadowRootInit(ShadowRootMode.OPEN))
        render()
    }

    override fun attributeChangedCallback(name: String, oldValue: Any?, newValue: Any?) {
        when (name) {
            "test" -> test = newValue.toString()
        }
        render()
    }

    fun render() {
        this.asDynamic().shadowRoot.innerHTML = "Test: counter = $varCounter $valCounter $constCounter, test=$test"
    }

    companion object {
        init {
            Test::class.js.register("test-test", "test")
        }

        private const val constCounter = 9000
    }
    
}
thanks for the tip!!