Skip to main content

Event Handling

There are three scenarios in which the use of Event Handlers is different in the Kotlin API:

  1. Event handlers in common props - event handlers are replaced by lambdas configured via Style.
  2. Providing EventHandlers to existing Spec components - when an EventHandler is expected, lambda should be wrapped with eventHandler {} or eventHandlerWithReturn {}.
  3. Accepting custom event handlers - custom Event classes are replaced by lambdas passed as props.

Each of these scenarios is detailed in the following sections.

Supplying event handlers​

Event handlers in common props​

Event handlers that were exposed in common props in the Spec API (such as clickHandler) are now provided via Style.

Style properties accept lambdas instead of generated EventHandler objects.

class EventComponent : KComponent() {
override fun ComponentScope.render(): Component? {
return Column(
style = Style.onClick { onClick() }.width(80.dp).height(80.dp).backgroundColor(YELLOW))
}
}

private fun onClick() {
Log.d("EventComponent", "click")
}

Providing EventHandlers to existing Spec components​

When using pre-existing Spec components or Sections that accept EventHandler objects for custom events (such as RenderEvent in DataDiffSection), you should use either eventHandler() or eventHandlerWithReturn(), depending on whether the custom event class declares a returnType in its @Event annotation or not. Both of these functions accept a lambda, which is invoked when the event occurs.

class SectionComponent(private val words: List<String>) : KComponent() {
override fun ComponentScope.render(): Component? {
return Column(style = Style.width(80.dp).height(80.dp)) {
child(
RecyclerCollectionComponent(
section =
DataDiffSection.create<String>(SectionContext(context))
.data(words)
.renderEventHandler(eventHandlerWithReturn { event -> onRender(event) })
.build()))
}
}

private fun ResourcesScope.onRender(event: RenderEvent<String>): RenderInfo {
return ComponentRenderInfo.create().component(Text(text = event.model)).build()
}
}

Accepting custom event handlers​

In the Spec API, custom event handlers can be defined by creating an Event class, and then either providing its type to the events param in the @LayoutSpec annotation or accepting an EventHandler as a prop, as detailed in the Events for Specs page. In the Kotlin API, simply accept a lambda as a prop to be invoked when the event happens:

class ClickEventComponent(
private val onButtonClicked: (String) -> Unit,
) : KComponent() {
override fun ComponentScope.render(): Component {
return Column {
child(Text(text = "OK", style = Style.onClick { onButtonClicked("OK clicked") }))
child(Text(text = "Cancel", style = Style.onClick { onButtonClicked("Cancel clicked") }))
}
}
}