Java Reference
In-Depth Information
Given a choice between bind or on replace , you'll almost always want to
choose bind . In addition to being more efficient, you'll have the added benefit of
avoiding the unsynchronized condition identified in the preceding example. In
general, on replace should only be used when there is no alternative. Triggers are
appropriate, for example, when state needs to be synchronized between JavaFX
and Java, or when there are ancillary effects that need to be dealt with resulting
from a change in the value of a variable. For example, if you need to run an ani-
mation sequence, your trigger might look like
var image: ImageView = bind ImageView {
image: currentImage
} on replace {
imageAnimation.play();
}
For the next example, we'll expand on trigger usage by introducing two addi-
tional capabilities. First, just like plain variables, triggers can also operate on
sequences. Second, the on replace phrase can be enhanced so that while exe-
cuting the trigger code block, you can access the old value of the variable being
replaced. In the example that follows, oldRainbow is an arbitrarily named vari-
able of the same type as rainbow . It appears directly after on replace , and upon
execution of the code block, it contains the value of rainbow before it is replaced.
Determining If a Variable or Instance Variable
Has Been Updated
As explained in an earlier sidebar, there may be times when you want to know
when an object has been recreated. Alongside that information, you may also want
to know when a variable or instance variable has been updated, possibly due to a
bind recalculation. In JavaFX, you can append a trigger with an associated block of
code onto a variable declaration such that whenever its value changes that code
will be executed. By defining an instance variable to look like
class MyClass {
public var attr : String on replace {
println("attr updated to {attr}");
}
}
you'll be able to know when attr changes because “ attr updated to … ” will be
printed out every time attr is modified.
Search WWH ::




Custom Search