90 lines
2.2 KiB
90 lines
2.2 KiB
2 years ago
|
# Events handling
|
||
4 years ago
|
|
||
|
You can add event listeners in the `attrs` block:
|
||
|
|
||
|
#### onClick
|
||
4 years ago
|
``` kotlin
|
||
4 years ago
|
Button(
|
||
|
attrs = {
|
||
3 years ago
|
onClick { event ->
|
||
|
// event is of `SyntheticMouseEvent` type
|
||
|
println("button clicked at ${event.movementX}, ${event.movementY}")
|
||
4 years ago
|
|
||
3 years ago
|
val nativeEvent = event.nativeEvent // [MouseEvent](https://developer.mozilla.org/en/docs/Web/API/MouseEvent)
|
||
4 years ago
|
}
|
||
|
}
|
||
|
) {
|
||
|
Text("Button")
|
||
|
}
|
||
|
```
|
||
|
|
||
|
#### onInput
|
||
4 years ago
|
``` kotlin
|
||
4 years ago
|
val text = remember { mutableStateOf("") }
|
||
|
|
||
|
TextArea(
|
||
|
value = text.value,
|
||
|
attrs = {
|
||
3 years ago
|
onInput {
|
||
|
text.value = it.value
|
||
4 years ago
|
}
|
||
|
}
|
||
|
)
|
||
|
```
|
||
|
|
||
4 years ago
|
|
||
|
#### Other event handlers
|
||
|
|
||
3 years ago
|
For events that don't have their own configuration functions in the `attrs` block, you can use `addEventListener` with the `name` of the event, `options`, and an pass an `eventListener` which receives a `SyntheticEvent`. In this example, we're defining the behavior of a `Form` element when it triggers the `submit` event:
|
||
4 years ago
|
|
||
4 years ago
|
``` kotlin
|
||
4 years ago
|
Form(attrs = {
|
||
|
this.addEventListener("submit") {
|
||
|
console.log("Hello, Submit!")
|
||
3 years ago
|
it.preventDefault()
|
||
4 years ago
|
}
|
||
|
})
|
||
|
```
|
||
|
|
||
4 years ago
|
|
||
2 years ago
|
There are more event listeners supported out of the box. You can find all supported event listeners in the [source code](https://github.com/JetBrains/compose-multiplatform/blob/master/html/core/src/jsMain/kotlin/org/jetbrains/compose/html/attributes/EventsListenerScope.kt).
|
||
4 years ago
|
|
||
|
|
||
|
### Runnable example
|
||
|
|
||
|
```kotlin
|
||
|
import androidx.compose.runtime.*
|
||
4 years ago
|
import org.jetbrains.compose.web.css.*
|
||
|
import org.jetbrains.compose.web.dom.*
|
||
|
import org.jetbrains.compose.web.renderComposable
|
||
4 years ago
|
|
||
|
fun main() {
|
||
|
renderComposable(rootElementId = "root") {
|
||
|
Button(
|
||
|
attrs = {
|
||
3 years ago
|
onClick { event ->
|
||
|
println("button clicked at ${event.movementX}, ${event.movementY}")
|
||
4 years ago
|
}
|
||
|
}
|
||
|
) {
|
||
|
Text("Button")
|
||
|
}
|
||
|
|
||
|
val text = remember { mutableStateOf("") }
|
||
|
|
||
|
TextArea(
|
||
|
value = text.value,
|
||
|
attrs = {
|
||
3 years ago
|
onInput {
|
||
|
text.value = it.value
|
||
4 years ago
|
}
|
||
|
}
|
||
|
)
|
||
|
|
||
|
Span {
|
||
|
Text("Typed text = ${text.value}")
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
```
|