lundi 16 mai 2016

Java equivalent for knockout.js computed observables?

With knockout.js computed observables it is possible to define a JavaScript observable that depends on other observables, using a functional expression, e.g.

var computedObservable = ko.computed(function(){ 
    return firtName() + lastName();
});

If one of the referenced observables (e.g. firstName) changes, the computed observable is automatically updated. The referenced observables are defined by the given functional expression and do not have to be explicitly specified.

How can I implement something similar in Java?

(Well, there are JavaFx Bindings, but they require the explicit registration of the referenced properties/observables.)

I distinguish two cases:

a) The given lambda expression is analyzed with Java to automatically find out which referenced observables have to be considered. (The referenced observables might reference further observables in a dependency chain.) Expected example code:

ComputedObservable computedObservable = new ComputedObservable(() -> {
    return firstName.get() + lastName.get();
}); 

b) I have to manually register each referenced observable to be able to observe them. I would like to avoid this case. With other words I do not want to have code like

ComputedObservable computedObservable = new CoputedObservable();
computedObservable.registerReference(firstName);
computedObservable.registerReference(lastName);
computedObservable.setExpresion(() -> {
        return firstName.get() + lastName.get();
});

or (using JavaFx Bindings)

 DoubleBinding db = new DoubleBinding() { 
        {
            super.bind(a, b, c, d);
        }

        @Override
        protected double computeValue() {
            return (a.get() * b.get()) + (c.get() * d.get());
        }
 };

Is case a) possible at all and if yes, is there an existing Java implementation/library for doing so?





Aucun commentaire:

Enregistrer un commentaire