There are no bidirectional bindings with converter...
# tornadofx
m
There are no bidirectional bindings with converters in TornadoFX?
r
Unfortunately not. There is actually an implementation for them (that is used for String converted bindings), but it's private.
👍 1
m
I implemented a poor man's version for myself:
Copy code
import javafx.beans.property.Property

import tornadofx.onChange

fun <A, B> Property<A>.bindBidirectionallyWith(other : Property<B>, converter: ITypeConverter<A, B>) =
    BidirectonalBinding(this, other, converter).apply { activate() }

// TODO: implement unbinding, using addListener and removeListener
class BidirectonalBinding<A, B>(
    val propertyA: Property<A>,
    val propertyB: Property<B>,
    val converter: ITypeConverter<A, B>
) {
    private var updating = false

    fun activate() {
        propertyA.onChange(::updatePropertyB)
        propertyB.onChange(::updatePropertyA)

        updatePropertyB(propertyA.value)
    }

    private fun updatePropertyA(b : B?) {
        if (!updating) {
            updating = true
            propertyA.value = if (b == null) {
                null
            } else {
                converter.convertToA(b)
            }
            updating = false
        }
    }

    private fun updatePropertyB(a : A?) {
        if (!updating) {
            updating = true
            propertyB.value = if (a == null) {
                null
            } else {
                converter.convertToB(a)
            }
            updating = false
        }
    }
}
r
I've done something similar a few years back. Let me know how unbinding goes for you. I had issues with it in my implementation.