Skip to main content

example of binding object attributes and functions that react to changes?

3 replies [Last post]
shahbazc
Offline
Joined: 2008-04-06
Points: 0

Say I have an object with four or five attributes. I would like to bind these attributes to some expression. Every time one of the attributes changes, a function is evaluated. In other words, say a function simply prints out the bound attributes. Every time an attribute changes, the values are printed again.

I would like to do this in a declarative manner -- in other words, I'd like to avoid wrapping attributes in 'setter' functions which then call the print function.

I'm not sure if it is possible, but I'd also like to avoid littering my code with onreplace triggers.

Basically I am trying to put a declarative interface on top of a very imperative code (the underlying application is actually a network based app).

Thanks

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
alexsch
Offline
Joined: 2007-07-12
Points: 0

Does it help?

[code]
class C{
public var a:Integer;
public var b:Integer;

public function add(a:Integer, b:Integer):Integer{
a + b
}
}

var c = C{
a: 3
b: 4 };

Stage {
title: "MyApp"
scene: Scene {
width: 300
height: 200
content: [
Text {
translateX: 5
translateY: 15
content: bind "a: {c.a}"
},
SwingSlider {
translateX: 40
minimum: 0
maximum: 9
value: bind c.a with inverse
},
Text {
translateX: 5
translateY: 45
content: bind "b: {c.b}"
},
SwingSlider {
translateY: 30
translateX: 40
minimum: 0
maximum: 9
value: bind c.b with inverse
},
Text {
translateX: 5
translateY: 75
content: bind "a + b = { c.add(c.a, c.b) }"
},
]
}
}
[/code]

shahbazc
Offline
Joined: 2008-04-06
Points: 0

Thanks, this is a great example!

I've never see the "with inverse" clause. Am I correct in assuming that it creates a two way binding between C and SwingSlider?

It looks like when a function is in a "bind" expression, every time one of it's arguments changes, the function is re-evaluated. Correct? I didn't expect this behavior since class C doesn't have any "bind" keywords in it.

alexsch
Offline
Joined: 2007-07-12
Points: 0

> Thanks, this is a great example!
>
> I've never see the "with inverse" clause. Am I
> correct in assuming that it creates a two way binding
> between C and SwingSlider?

Yes, you are.

>
> It looks like when a function is in a "bind"
> expression, every time one of it's arguments changes,
> the function is re-evaluated. Correct? I didn't
> expect this behavior since class C doesn't have any
> "bind" keywords in it.

See the Binding chapter in the JavaFX Language Reference document:
http://openjfx.java.sun.com/current-build/doc/reference/Binding.html