Add onClick to Button in Ktor with Kotlinx

1k Views Asked by At

I am currently trying out Ktor. But it already fails on registering a onClickListener to the button.

I am just wondering because the onClick extends from String. If I click on the onClick the Code I get is this one:

var CommonAttributeGroupFacade.onClick : String
    get()  = attributeStringString.get(this, "onclick")
    set(newValue) {attributeStringString.set(this, "onclick", newValue)}

So I think onClick has a getter and setter but not more. I installed location and FreeMarker so this is my route:

get<CharityRoute> {
            val id = it.id
            call.respondHtml {
                body {
                    h1 { +"${it.id}" }
                    ul {
                        for (n in it.list) {
                            li { +"$n" }
                        }
                    }
                    button {
                        text("Run function")
                        onClick = "Hello"
                    }
                }
            }
        }

Maybe someone has more experience with Ktor and especially with Kotlinx.

1

There are 1 best solutions below

1
On

Problem It depends which module you are working in.

On the server-side (JVM) you can not write Javascript-Code in Kotlin and assign it to a function like that.

To find a solution, I have to further know, what exactly it is you want to achieve.

Here are two of many possibilities, what you could do:

Solution 1 You can assign a javascript-code as string. You did just that by assigning the code "Hello". Maybe you want to call a function, which was globally made available in the window object?

Solution 2 In client-side JS code, you can import kotlinx.html.js.onClickFunction and simply write

button{
  onClickFunction = { println("clicked") }
}

to execute code written in Kotlin.