Data binding using bind and on replace in JavaFx

Data binding using bind and on replace:
bind:
bind is a keyword used to bind a value of a variable to some other expression.
For example:

var a = 64;
var b = bind {a/8};

The value of variable b in the above expression is bound to the value of variable a.
In the case above the value of b is 8.

var a = 64;
var b = bind {a/8};
a = 64 * 8;
println("value of b  is :{b}"};

When the above code is executed the value of variable b will be printed as 64. So, the value of variable b changes accordingly every time the value of variable a changes.

on replace:
on replace is usually used when certain actions need to be taken once the value of the variable is changed.
For example:

var a = 64;
var b = bind {a/8} on replace { if (a > 64) a = 10};
a = 64 * 8;
println("value of b  is :{b}"};

The above block of code replaces the value of variable a from 64*8 to 64 once the value of b is printed from the last line. When the second line is executed the value of variable a remains unchanged because variable a has the value of 64. However when the last line is executed the value of variable at that moment is 64 * 8 which is greater than 64. So, when variable b gets the value 64 the value of variable a is also changed to 10.

Advertisements