简体   繁体   中英

How to create multilevel composition binding?

I was shown how to create a dependency on the containing property of a property using something like Val.selectVar(property, propertyOfProperty) . However, i want to know how to continue creating dependencies on the composition graph. so like a property of a property of a property etc.

Here is an example of what I know and what I want:

import org.reactfx.value.Val;
import org.reactfx.value.Var;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;

class Level1 {
    private ObjectProperty<Level2> l2 = new SimpleObjectProperty<>(new Level2());
    ObjectProperty<Level2> l2Property() { return l2; }
}

class Level2 {
    private ObjectProperty<Level3> l3 = new SimpleObjectProperty<>(new Level3());
    ObjectProperty<Level3> l3Property() { return l3; }
}

class Level3 {
    private ObjectProperty<Level4> l4 = new SimpleObjectProperty<>(new Level4());
    ObjectProperty<Level4> l4Property() { return l4; }
}

class Level4 {
    private IntegerProperty ip = new SimpleIntegerProperty();
    IntegerProperty ipProperty() { return ip; }
}

public class Example3 {

    Example3() {
        Level1 l1 = new Level1();
        Level2 l2 = l1.l2Property().get();
        Level3 l3 = l2.l3Property().get();
        Level4 l4 = l3.l4Property().get();
        Var<Number> ipVar = Val.selectVar(l3.l4Property(), Level4::ipProperty);
        ipVar.addListener((ob, o, n) -> System.out.println(o + " -> " + n));

        l4.ipProperty().set(1); // prints "0 -> 1"

        Level4 newL4 = new Level4();
        newL4.ipProperty().set(2);
        l3.l4Property().set(newL4);  // prints "1 -> 2"

//      Something that does this
//      ipVar2.listenTo(l2.l3Property(), l1.l2Property());
//      or this
//      Var<Number> ipVar2 = Val.selectVarAll(l1.l2Property(), l2.l3Property(), l3.l4Property(), Level4::ipProperty);

        Level3 newL3 = new Level3();
        l2.l3Property().set(newL3); // I want: prints "2 -> 0"

//      level2 etc.
    }

    public static void main(String[] args) {
        new Example3();
    }
}

Basically, i want to know when a property changes by changes anywhere in the properties containing it and not just the direct one.

Doesn't

Var<Number> ipVar2 = Val.selectVar(l1.level2Property(), Level2::level3Property)
    .selectVar(Level3::level4Property)
    .selectVar(Level4::ipProperty);

give you what you need?

(If you only need an ObservableValue instead of a Property - ie if you only need to observe and not write to the value - you can use flatMap instead of selectVar throughout.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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