jeudi 27 juin 2013

FXBinding, the binding you need

JavaFX 2 brings the Properties and Bindings concepts. If you don't know what I am talking about, I suggest you to have a look here : binding

I have an List ObservableList<XYChart.Data<Number, Number>>. I want to compute the average value of XValueProprerty for all Data contained into the list :


Without FXBinding :

See full code here

As you can see, it doesn't work :/

The binding is invalid only when the list changes, so when the XValue of a Data changes, nothing append.

I have to register every XValueProperty() into the bind() method :

See full code here

Now it works for all Data that was into the list at the beginning, but not for all added (or removed) Data after the init of the Binding

Let's make it work :

See full code here

While the complexity of your model is growing, you will have to register many listeners and the code is going to be less readable, less maintainable and less bug proof.


With FXBinding

Now let's replace our DoubleBinding by a magical FXDoubleBinding, it's 4 time step :

  • Replace new DoubleBinding() by new FXDoubleBinding()
  • Change the method name from computeValue() to compute()
  • Remove {bind(...)} and replace it by the configure() method
  • In the configure() method call addObservable() instead of bind()
See full code here

Every time the binding is becoming invalid, we will reconfigure it, so it's always a cool binding.

We will never have to add a listener even in a very complex model

An other example :

See full code here

Get FXBinding here

Aucun commentaire:

Enregistrer un commentaire