简体   繁体   English

JavaFX:绑定和弱监听器

[英]JavaFX: Binding and weak listener

From Javadoc for bind() : Javadoc中获取bind()

Note that JavaFX has all the bind calls implemented through weak listeners. 请注意,JavaFX具有通过弱侦听器实现的所有绑定调用。 This means the bound property can be garbage collected and stopped from being updated. 这意味着可以对垃圾属性进行垃圾收集,并阻止其更新。

Now consider that I have two properties ObjectProperty<Foo> shortLived residing in ShortLivedObject and ObjectProperty<Foo> longLived residing in LongLivedObject . 现在考虑拥有两个属性, ObjectProperty<Foo> shortLived位于ShortLivedObject ObjectProperty<Foo> longLived和位于ShortLivedObject ObjectProperty<Foo> longLived LongLivedObject

I am binding them like this: 我这样绑定它们:

longLivedObject.longLivedProperty().bind(shortLivedObject.shortLivedProperty());

Because binding uses weak listener, so if shortLivedObject is garbage collected, shortLived property would be garbage collected as well. 因为绑定使用弱监听器,所以如果将shortLivedObject进行垃圾回收, shortLived属性进行垃圾回收。 So, does that means that longLived property is still bound, but it will never be updated? 那么,这是否意味着longLived属性仍然被绑定,但是它永远不会被更新? Does that leave longLived property in a bound state (making further binding impossible), but does nothing? 这是否会使longLived属性处于绑定状态(使进一步的绑定成为不可能),但是什么也不做呢?

So, does that means that longLived property is still bound, but it will never be updated? 那么,这是否意味着longLived属性仍然被绑定,但是它永远不会被更新?

Assuming that the shortLivedProperty has been garbage collected, the shortLivedProperty will never be invalidated again. 假设shortLivedProperty已被垃圾回收, shortLivedProperty将永远不会再次失效。 As a result, the listener of the longLived will never be called and updated again. 结果,将不再调用longLived的侦听器并对其进行更新。

Does that leave longLived property in a bound state (making further binding impossible), but does nothing? 这是否会使longLived属性处于绑定状态(使进一步的绑定成为不可能),但是什么也不做呢?

You should always be able to bind a property to a new observable regardless of the binding state as the old observable property will be removed/unbound for you: 无论绑定状态如何,您都应该始终能够bind属性bind新的可观察对象,因为旧的可观察属性将为您删除/取消绑定:

public void bind(final ObservableValue<? extends T> newObservable) {
    if (newObservable == null) {
        throw new NullPointerException("Cannot bind to null");
    }

    if (!newObservable.equals(this.observable)) {
        unbind();
        observable = newObservable;
        if (listener == null) {
            listener = new Listener(this);
        }
        observable.addListener(listener);
        markInvalid();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM