Hi there,
I wanted to put together a little demo where the onfocus handler of an input prints some message that contains the input's value.
V1
val inputElem : HTMLInputElement = input(
`type` := "text",
onfocus := { (e: FocusEvent) => {
println(s"Hi from inputElem.onfocus. value: ${inputElem.value}")
}
}
).render
However I cannot do this and the compiler complains:
[error] /Users/christoph/code/scalajs-test/src/main/scala/Main.scala:28: forward reference extends over definition of value inputElem
[error] println(s"Hi from inputElem.onfocus. value: ${inputElem.value}")
So the problem is that inputElem is really assigned after render was called. And I am trying to access it before that. The callback in which I am accessing it actually runs later.
V2
One way to do is to declare a var and reassign it:
var inputElem2 : HTMLInputElement = null
inputElem2 = input(
`type` := "text",
onfocus := { (e: FocusEvent) => {
println(s"Hi from inputElem2.onfocus. value: ${inputElem2.value}")
}
}
).render
V3
Another way to do it is by getting the element from the event, but I need to cast and I suppose this does not work in other situations.
val inputElem3 = input(
`type` := "text",
onfocus := { (e: FocusEvent) => {
println(s"Hi from inputElem3.onfocus. value: ${e.target.asInstanceOf[HTMLInputElement].value}")
}
}
).render
Is there a more elegant solution? Currently, I would go with version 2.