All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.jetbrains.datalore.base.observable.property.PropertyBinding.kt Maven / Gradle / Ivy

There is a newer version: 4.5.3-alpha1
Show newest version
/*
 * Copyright (c) 2019. JetBrains s.r.o.
 * Use of this source code is governed by the MIT license that can be found in the LICENSE file.
 */

package jetbrains.datalore.base.observable.property

import jetbrains.datalore.base.observable.event.EventHandler
import jetbrains.datalore.base.registration.CompositeRegistration
import jetbrains.datalore.base.registration.Registration

/**
 * One and two-way property binding support
 */
object PropertyBinding {
    fun  bindOneWay(
            source: ReadableProperty, target: WritableProperty): Registration {
        target.set(source.get())
        return source.addHandler(object : EventHandler> {
            override fun onEvent(event: PropertyChangeEvent) {
                @Suppress("UNCHECKED_CAST")
                target.set(event.newValue as ValueT)
            }
        })
    }

    fun  bindTwoWay(source: Property, target: Property): Registration {
        val syncing = ValueProperty(false)
        target.set(source.get())

        class UpdatingEventHandler(private val myForward: Boolean) : EventHandler> {

            override fun onEvent(event: PropertyChangeEvent) {
                if (syncing.get()) return

                syncing.set(true)
                try {
                    if (myForward) {
                        target.set(source.get())
                    } else {
                        source.set(target.get())
                    }
                } finally {
                    syncing.set(false)
                }
            }
        }

        return CompositeRegistration(
                source.addHandler(UpdatingEventHandler(true)),
                target.addHandler(UpdatingEventHandler(false))
        )
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy