Skip to content
Alexander Nemish edited this page Aug 13, 2013 · 4 revisions

In most cases, JScala translates Scala code to Javascript literally:

val x = 2
println(javascript(x).asString)

will print x. When you need an actual value inside generated Javascript you need to inject it:

val x = 2
println(javascript(inject(x)).asString) // prints 2

inject looks for a type class JsSerializer[A] implementation for some A, (Int in previous example). There are bunch of predefined JsSerializer for common types: Int, Double, String etc. You can easily define your own JsSerializer to be able to inject values:

case class My(a: String)
implicit def zzz: JsSerializer[My] = new JsSerializer[My] { def apply(a: My) = JsString(a.a) }
val z = My("my")
javascript {
  val a = inject(z)
}

will produce

var a = "my";

Injecting a function

There is a predefined JsSerializer[() => A], so you can call a function every time asString, eval or compress is called.

def f() = Random.nextString(2)
val js = javascript {
  val a = inject(f _)
  a
}
js.asString // var a = "Rn"
js.eval() // "Vq"

Injecting JScala AST

If you have a function (...) => JsAst you can inject its result directly

def foo() = javascript(2)
def bar() = JsString("3")
javascript {
  val two = foo()
  val three = bar()
}

translates to

var two = 2;
var three = "3";

Clone this wiki locally