JavaFX: Bound functions

Binding in JavaFX is of course very cool, and in most circumstances it makes sense. I thought I would make a quick post to explain what a bound function is, and how you should go about interpreting code that uses this language feature. I want to make this post as simple as possible, so as to not overcomplicate things. Before I begin I must thank the Pro JavaFX Platform book guys - I base this explanation on code from their (highly recommended) book.

A bound function looks like this:

var x = 3;
bound function f(y:Number, z:Number):Number {
  var u = y;
  var v = z;
  x + u

The interesting thing about this function declaration is the bound keyword. Looking at the body of the function, we note that the function makes use of variables y and z from the function, and assigns these to variables u and v respectively. In actual fact, the z argument is never used, but an x value is used. This x value is declared outside the function, and is therefore available to be used by it.

This function can be used as per usual in our code simply by calling f(1,2), for example. The feature that is offered by the bound modifier is that we can bind to the function, and when the x or y variables values change, the function will re-evaluate itself. An example is shown in the code below:

var a = 4;
var b = 5;
var c = bind f(a, b);

On line 3, c is bound to equal the result of calling the function f(a, b), which will result in c being set to equal 7.0 (as a=4,b=5, and x=3, and f is the sum of a and x).

Line four changes the value of x from 3 to 5. Because the f function is a bound function, and the c variable is bound to the f function, we re-evaluate f(a, b), and assign the new value of a+x to c, which means that c is now equal to 9.0.

Similarly, when the a variable is changed on line 5, the function is re-evaluated, as it has determined that the value of a is relevant to the value stored in c.

As noted previously, the value of b is not used in the function, and therefore when it changes it does not impact on the value of the variable stored in c. Because of this, when the value of b is changed on line 6, c is not re-evaluated, as JavaFX is smart enough to know that this does not matter.

If the c variable was declared as f(a, b) (i.e. it is not bind f(a, b)), then when x is updated, c will not be recalculated. Similarly, if the function declaration for f is not declared to be bound, c will not be updated either. However, both of these permutations are legal syntax - it just results in different outcomes. To have f re-evaluate itself and the value be assigned to c, it is necessary the both the function be declared bound, and the assignment to variable c be bound (using the bind keyword).

I hope that makes sense, and clarifies the purpose of the bound keyword.

Thoughts on “JavaFX: Bound functions”