Is it possible to bind a Range(Input) to a complex...
# kvision
t
Is it possible to bind a Range(Input) to a complex ObservableValue (data class)? Tried also (without success) to bind to a sub-store.
r
If you are referring to bidirectional binding to a
MutableState
you can't do this directly. KVision doesn't provide a
sub
equivalent for
MutableState
.
But you can fairly easy implement you own mutable sub-store.
Check this code:
Copy code
data class State(val range: Int, val other: String)

        val mainState = ObservableValue(State(5, "test"))

        val subState = object : MutableState<Int> {
            override fun setState(state: Int) {
                mainState.setState(mainState.getState().copy(range = state))
            }

            override fun getState(): Int {
                return mainState.getState().range
            }

            override fun subscribe(observer: (Int) -> Unit): () -> Unit {
                return mainState.subscribe {
                    observer(it.range)
                }
            }
        }

        root("kvapp") {
            div().bind(mainState) {
                +"Range: ${it.range}"
            }
            range(min = 0, max = 10).bindTo(subState)
            button("test").onClick {
                subState.setState(8)
            }
        }