melatonina
09/11/2020, 9:27 AMRuckus
09/11/2020, 1:39 PMmelatonina
09/11/2020, 4:15 PMimport 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
}
}
}
Ruckus
09/11/2020, 4:17 PM