qed
qed

Reputation: 23154

Bidirectional binding fails to bind

Here is an example from Pro ScalaFX:

package proscalafx.ch03

import scalafx.beans.property.StringProperty

object BidirectionalBindingExample extends App {
  println("Constructing two StringProperty objects.")
  val prop1 = new StringProperty("")
  val prop2 = new StringProperty("")

  println("Calling bindBidirectional (<==>).")
  prop2 <==> prop1

  println("prop1.isBound = " + prop1.isBound)
  println("prop2.isBound = " + prop2.isBound)

  println("Calling prop1.set(\"prop1 says: Hi!\")")
  prop1() = "prop1 says: Hi!"
  println("prop2.get returned:")
  println(prop2())

  println( """Calling prop2.set(prop2.get + "\nprop2 says: Bye!")""")
  prop2() = prop2() + "\nprop2 says: Bye!"
  println("prop1.get returned:")
  println(prop1())
}

The two StringProperty objects are supposed to be bound with each other, when one of them is updated, the other should be also updated. This isn't true here:

Constructing two StringProperty objects.
Calling bindBidirectional (<==>).
prop1.isBound = false
prop2.isBound = false
Calling prop1.set("prop1 says: Hi!")
prop2.get returned:
prop1 says: Hi!
Calling prop2.set(prop2.get + "\nprop2 says: Bye!")
prop1.get returned:
prop1 says: Hi!
prop2 says: Bye!

Upvotes: 0

Views: 138

Answers (1)

Jarek
Jarek

Reputation: 1533

There is no problem with this code. prop1 and prop2 are bi-directionally bound to each other. When you look at the output you provided it is clearly the case. When value of prop1 was set to "prop1 says: Hi!" value of prop2 changes to it too, and when you change prop2 then prop1 is changing. Please look carefully at the output.

One thing that may be confusing is that isBound returns false for both properties. This is correct behaviour for bi-directional binding. isBound will return true only if a property is uni-directionally bound to another. So if you would change the code to:

prop2 <== prop1
println("prop1.isBound = " + prop1.isBound)
println("prop2.isBound = " + prop2.isBound)

You would get

prop1.isBound = false
prop2.isBound = true

This is how JavaFX works, nothing to do with ScalaFX.

Upvotes: 1

Related Questions