2008年12月13日土曜日

JavaFX Data Binding and Triggers

Binding and Objects

変数同士を関連づけて、一方の値が変わると、もう一方も変わるのが Binding

var x = 0;
def y = bind x;
x = 1;
println(y); // y now equals 1
x = 47;
println(y); // y now equals 47

Address も bind できる

var myStreet = "1 Main Street";
var myCity = "Santa Clara";
var myState = "CA";
var myZip = "95050";

def address = bind Address {
street: myStreet;
city: myCity;
state: myState;
zip: myZip;
};

println("address.street == {address.street}");
// address.street == 1 Main Street
myStreet = "100 Maple Street";
println("address.street == {address.street}");
// address.street == 1 Main Street

この場合、新しい Object が作成されるが、 Object を作成しない方法もある

def address = bind Address {
street: bind myStreet;
city: bind myCity;
state: bind myState;
zip: bind myZip;
};

この場合、最初の bind を省略することができる

def address = Address {
street: bind myStreet;
city: bind myCity;
state: bind myState;
zip: bind myZip;
};



Binding and Functions

var scale = 1.0;

bound function makePoint(xPos : Number, yPos : Number) : Point {
Point {
x: xPos * scale
y: yPos * scale
}
}

class Point {
var x : Number;
var y : Number;
}

var myX = 3.0;
var myY = 3.0;
def pt = bind makePoint(myX, myY);
println(pt.x); // 3.0

myX = 10.0;
println(pt.x); // 10.0

scale = 2.0;
println(pt.x); // 20.0

bound を外すと、最後の出力は 10.0 になる


Binding with Sequences

var seq1 = [1..10];
def seq2 = bind for (item in seq1) item*2;
printSeqs();

function printSeqs() {
println("First Sequence:");
for (i in seq1){println(i);}
println("Second Sequence:");
for (i in seq2){println(i);}
}

/* output
First Sequence:
1
2
3
4
5
6
7
8
9
10
Second Sequence:
2
4
6
8
10
12
14
16
18
20
*/


seq1 に item を追加すると、seq2 も変わる

var seq1 = [1..10];
def seq2 = bind for (item in seq1) item*2;
insert 11 into seq1;
printSeqs();

function printSeqs() {
println("First Sequence:");
for (i in seq1){println(i);}
println("Second Sequence:");
for (i in seq2){println(i);}
}

/*
First Sequence:
1
2
3
4
5
6
7
8
9
10
11
Second Sequence:
2
4
6
8
10
12
14
16
18
20
22
*/



Replace Triggers

任意の変数をトリガーに使うことができる
次のコードは password 変数が変更されると、メッセージが表示される

var password = "foo" on replace oldValue {
println("\nALERT! Password has changed!");
println("Old Value: {oldValue}");
println("New Value: {password}");
};

password = "bar";

/* output
ALERT! Password has changed!
Old Value:
New Value: foo

ALERT! Password has changed!
Old Value: foo
New Value: bar
*/

0 件のコメント:

コメントを投稿