Java Reference
In-Depth Information
along the line the fruits of their labors must be synchronized. This is where the
concept of binding comes into play.
If, for example, you want the appearance of your user interface to reflect some
state change in your logic, or vice versa, you'll need a way for those differences
to percolate over to one another. In JavaFX, the bind keyword is introduced to
facilitate this capability. The act of binding a variable associates that variable
with an expression, such that whenever the value of the expression changes, its
bound variable will automatically change too. This simple yet powerful principle
is all that's needed to connect previously disparate models together.
More formally stated, the bind keyword associates the value of a target variable
with the value of a remote variable. Binding in JavaFX follows this general syntax:
var v = bind expression ;
where expression can be as trivial as another variable or can include a range of
legal JavaFX expressions. When the expression on the right hand side of the
bind statement changes, a minimal recalculation takes place. We'll examine how
binding affects each type of expression and what actually gets calculated on
update.
Binding to Variables
Starting with the simplest case first and working our way toward the more com-
plex, the code that follows demonstrates binding in perhaps its most trivial case,
namely binding of a variable to another variable:
var x : Integer = 10;
var y = bind x;
var z = x; // z is not bound to x
println("x={x}, y={y}, z={z}");
x = 20;
println("x={x}, y={y}, z={z}");
In the preceding example, the variable x is declared as an Integer and assigned
an initial value of 10. A second variable y is declared and bound to variable x .
Because it is bound to x , the type of y is inferred to be Integer without having to
actually declare it as such. When the value of x changes, it forces y to be recalcu-
lated—in this instance, reassigned the new value of x .
The statement binding y to x is an example of unidirectional binding , meaning
that there is a one-way relationship between x and y . When x changes, y changes,
but y on the other hand has no influence on x whatsoever. By default, all binds
 
Search WWH ::




Custom Search