关于java:JavaFX:绑定和弱监听

JavaFX: Binding and weak listener

来自 bind() 的 Javadoc:

Note that JavaFX has all the bind calls implemented through weak
listeners. This means the bound property can be garbage collected and
stopped from being updated.

现在考虑我有两个属性 ObjectProperty<Foo> shortLived 驻留在 ShortLivedObjectObjectProperty<Foo> longLived 驻留在 LongLivedObject.

我是这样绑定它们的:

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

因为绑定使用弱监听,所以如果 ShortLivedObject 被垃圾回收,shortLived 属性也会被垃圾回收。那么,这是否意味着 longLived 属性仍然被绑定,但它永远不会被更新?这是否使 longLived 属性处于绑定状态(使进一步绑定变得不可能),但什么也不做?


So, does that means that longLived property is still bound, but it
will never be updated?

假设 shortLivedProperty 已被垃圾回收,则 shortLivedProperty 将永远不会再次失效。因此,longLived 的侦听器将永远不会被再次调用和更新。

Does that leave longLived property in a bound state (making further
binding impossible), but does nothing?

无论绑定状态如何,您都应该始终能够 bind 将属性添加到新的 observable,因为旧的 observable 属性将为您删除/解除绑定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
    }
}