How to do self-referencing elements

46 views
Skip to first unread message

Christoph Dietze

unread,
Oct 6, 2014, 6:09:30 PM10/6/14
to scal...@googlegroups.com
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.

Haoyi Li

unread,
Oct 6, 2014, 7:11:12 PM10/6/14
to Christoph Dietze, scal...@googlegroups.com
V1 works if you make it a lazy val

Not great, but that's Scala for you. I'd say V1 with lazy val would be the best way.

--
You received this message because you are subscribed to the Google Groups "Scalatags" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatags+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Christoph Dietze

unread,
Oct 7, 2014, 5:29:31 PM10/7/14
to scal...@googlegroups.com, christop...@gmail.com
That works nicely, thanks.
Reply all
Reply to author
Forward
0 new messages