1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package advanced
import org.scalajs.dom
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
import rx._
import scalatags.JsDom.all._
@JSExport
object BasicRx {
@JSExport
def main(container: dom.HTMLDivElement) = {
val txt = Var("")
val numChars = Rx{txt().length}
val numWords = Rx{
txt().split(' ')
.filter(_.length > 0)
.length
}
val avgWordLength = Rx{
txt().count(_ != ' ') * 1.0 / numWords()
}
val txtInput = textarea.render
txtInput.onkeyup = (e: dom.Event) => {
txt() = txtInput.value
}
container.appendChild(
div(
txtInput,
ul(
li("Chars: ", numChars),
li("Words: ", numWords),
li("Word Length: ", avgWordLength)
)
).render
)
}
@JSExport
def main2(container: dom.HTMLDivElement) = {
val fruits = Seq(
"Apple", "Apricot", "Banana", "Cherry",
"Mango", "Mangosteen", "Mandarin",
"Grape", "Grapefruit", "Guava"
)
val query = Var("")
val txtInput = input.render
txtInput.onkeyup = (e: dom.Event) => {
query() = txtInput.value
}
val fragments =
for(fruit <- fruits) yield Rx {
val shown = fruit.toLowerCase
.startsWith(query())
if (shown) li(fruit)
else li(display := "none")
}
container.appendChild(
div(
txtInput,
ul(fragments)
).render
)
}
implicit def rxFrag[T <% Frag](r: Rx[T]): Frag = {
def rSafe: dom.Node = span(r()).render
var last = rSafe
Obs(r, skipInitial = true){
val newLast = rSafe
js.Dynamic.global.last = last
last.parentNode.replaceChild(newLast, last)
last = newLast
}
last
}
}
|