score:6

Accepted answer

In Scala.js, scala.FunctionNs can be converted implicitly to js.FunctionNs and back, so you basically don't need to do anything: just pass in a lambda to the JavaScript call. There is an example of this in Step 5 of the the tutorial, under "Setup UI in Scala.js". For your code, it would look like this:

jQuery(dom.document).ready { () =>
  val svgContainer = ...
}

You can find more information on this in the calling JavaScript guide.

Update:

Here is the translation of your entire JavaScript snippet:

import scala.scalajs.js
import org.scalajs.dom           // see https://github.com/scala-js/scala-js-dom
import org.scalajs.jquery.jQuery // see https://github.com/scala-js/scala-js-jquery

object ScalaJSExample extends js.JSApp {
  val d3 = js.Dynamic.global.d3 // assuming you don't have static types for d3, here

  def main(): Unit = {
    jQuery(dom.document).ready { () =>
      val svgContainer =
        d3.select("body").append("svg")
          .attr("width", 1200)
          .attr("height", 1200)
          .attr("text-align", "center")
      testFunction(svgContainer)
    }
  }

  def testFunction(svgContainer: js.Dynamic): Unit = {
    dom.alert(svgContainer.toString())
  }
}

As you can see:

  1. For libraries that have static types for Scala.js (e.g., DOM and jQuery), it is best to use these static types. Here is use ready(), dom.document and dom.alert in a statically typed fashion.
  2. When you don't have static types, you can use js.Dynamic to manipulate JavaScript values in a dynamically typed way, using the normal syntax (not strings)
  3. You define functions with def. It shouldn't matter to you whether they are compiled as JavaScript functions or not: just write your Scala code without thinking about it, the compiler will do its job.

Related Query

More Query from same tag