|
Spec-Zone .ru
спецификации, руководства, описания, API
|
Bidirectional bind allows updates to flow in either direction, rather than just from the bound expression to the variable, as we have discussed above.
var z = bind x with inverse;
Here, as before, if x changes, z is updated to the value of x. But, the with inverse, means that if z is assigned to (or otherwise changed) then the value of x will be changed to the value of z. For example:
var note = "do";
var solfege = bind note with inverse;
println( "note={note}, solfege={solfege}" );
note = "re";
println( "note={note}, solfege={solfege}" );
solfege = "mi";
println( "note={note}, solfege={solfege}" );
note = "fa";
println( "note={note}, solfege={solfege}" );
| as with unidirectional bind, changing the bound expression changes the variable | |
| but, with bidirectional bind, changing the bound variable changes the bound expression, specifically the variable that is the bound expression |
note=do, solfege=do note=re, solfege=renote=mi, solfege=mi
note=fa, solfege=fa
Note that because it must be assignable, the bound expression is restricted to being a reference to a variable. This restriction makes bidirectional bind rather uninteresting for local variables, as they are just another name for the same value (as in the example above). Where they become interesting is in bindings between instance variables of objects. In this example, the instance variable x of the Point projectionOnX is bidirectionally bound to the instance variable of another point (pt).
class Point {
var x : Number;
var y : Number;
override function toString() : String { "Point({x},{y})" }
}
def pt = Point {
x: 3.0
y: 5.0
}
def projectionOnX = Point {
x: bind pt.x with inverse
y: 0.0
}
println( pt );
println( projectionOnX );
pt.x = 7.6;
println( pt );
println( projectionOnX );
projectionOnX.x = 22.2;
println( pt );
println( projectionOnX );
| as with unidirectional bind, changing the bound expression changes the instance variable | |
| but, with bidirectional bind, changing the bound variable changes the bound expression, specifically the instance variable that is the bound expression |
Point(3.0,5.0) Point(3.0,0.0) Point(7.6,5.0) Point(7.6,0.0)Point(22.2,5.0)
Point(22.2,0.0)
This is particularly useful in user interactions, for example displaying a stored value in an editable field. If the stored value changes, the displayed value should change, but also if the user edits the value, it should be stored.