Created
April 20, 2015 21:46
-
-
Save GabrielJones646/79fe9a09b7827451a2d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.{Failure, Success, Random} | |
import org.scalajs.dom.{Element, DOMParser} | |
import rx._ | |
object Framework { | |
/** | |
* Wraps reactive strings in spans, so they can be referenced/replaced | |
* when the Rx changes. | |
*/ | |
implicit def RxStr[T](r: Rx[T])(implicit f: T => Frag): Frag = { | |
rxMod(Rx(span(r()))) | |
} | |
/** | |
* Sticks some Rx into a Scalatags fragment, which means hooking up an Obs | |
* to propagate changes into the DOM via the element's ID. Monkey-patches | |
* the Obs onto the element itself so we have a reference to kill it when | |
* the element leaves the DOM (e.g. it gets deleted). | |
*/ | |
implicit def rxMod[T <: dom.raw.HTMLElement](r: Rx[HtmlTag]): Frag = { | |
def rSafe = r.toTry match { | |
case Success(v) => v.render | |
case Failure(e) => span(e.toString, backgroundColor := "red").render | |
} | |
var last = rSafe | |
Obs(r, skipInitial = true){ | |
val newLast = rSafe | |
last.parentElement.replaceChild(newLast, last) | |
last = newLast | |
} | |
bindNode(last) | |
} | |
implicit def RxAttrValue[T: AttrValue] = new AttrValue[Rx[T]]{ | |
def apply(t: Element, a: Attr, r: Rx[T]): Unit = { | |
Obs(r){ implicitly[AttrValue[T]].apply(t, a, r())} | |
} | |
} | |
implicit def RxStyleValue[T: StyleValue] = new StyleValue[Rx[T]]{ | |
def apply(t: Element, s: Style, r: Rx[T]): Unit = { | |
Obs(r){ implicitly[StyleValue[T]].apply(t, s, r())} | |
} | |
} | |
} | |
import Framework._ | |
object ScalaJSExample extends js.JSApp{ | |
def main() = { | |
val a = Var(1) | |
val b = Var(2) | |
val c = Rx{ a() + b() } | |
dom.document.querySelector("#output").appendChild{ | |
div( | |
div("a: ", a), | |
div("b: ", b), | |
div("c: ", c) | |
// div("d: ", d) | |
// div("e: ", e) | |
).render | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment