Scala.js – Passing simple values to JavaScript functions
Problem
You need to pass simple values (String, Int, Boolean) to JavaScript functions.
Solution
Let us illustrate the case by writing some functions on the host-page.
Edit index-dev.html
and add the following:
<script type="text/javascript">
function happyNew(name, year) {
alert("Hey " + name + ", happy new " + year + "!");
}
</script>
As we saw in the recipe of accessing the global scope, we need to make the following import:
import scala.scalajs.js
import js.Dynamic.{ global => g }
Now on the Scala side you can call it like this:
def main(): Unit = {
g.happyNew("Martin", 2014)
}
Which will result in the values being used and the corresponding alert being shown.
How does this work?
If your IDE shows the use of implicits, you’ll note that two implicit conversions are in play here:
- fromString
- fromInt
These are defined inside of Scala.js’s js.Any
. This is an excerpt of that:
package scala.scalajs.js
...
/** Provides implicit conversions from Scala values to JavaScript values. */
object Any {
...
implicit def fromInt(value: scala.Int): Number = sys.error("stub")
implicit def fromLong(value: scala.Long): Number = value.toDouble
implicit def fromFloat(value: scala.Float): Number = sys.error("stub")
implicit def fromDouble(value: scala.Double): Number = sys.error("stub")
...
implicit def fromString(s: java.lang.String): String = sys.error("stub")
...
}
Important
Note that Number
and String
you see here are not the ones of the Scala type hierarchy! Though not seen in the code, in reality they are js.Number
, js.String
, js.Boolean
, etc. which map to the real JavaScript types (String, Number, Boolean, etc.)
You NEVER pass Scala values or object instances to JavaScript (except some cases). Instead, these implicit functions convert from the Scala type to the JavaScript type seamlessly.
The fact that you don’t see it (thanks to implicit conversions) does not mean it’s not there. It is there and needs to be there.
Other types
In other recipes we’ll cover cases like passing collections or anonymous functions.