ScalaJS 终于给跑起来了😂

分享 未结
1 1 3 216
如宾 2021-01-20发布
收藏 点赞

知道Scala有JS版本时就心心念念想试试,但对于小白来说感觉官网教程无从下手 ,心里一直惦记着,这不今天又去看了一遍,试着试着就跑起来了!

效果图


构建项目

其实也不是自己从零开始搭建的环境,官方推荐的模板

$ sbt new vmunier/play-scalajs.g8
$ cd play-scalajs
$ sbt
> project server
> run
$ open http://localhost:9000


用 Dynamic 调用本地JS方法


测试代码

ScalaJSExample.scala

package com.example.playscalajs

import org.scalajs.dom
import org.scalajs.dom.{Event, XMLHttpRequest, console}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.Promise
import scala.util.Success

object ScalaJSExample {

  def main(args: Array[String]): Unit = {
    // dom.document.getElementById("scalajsShoutOut").textContent = SharedMessages.itWorks
    val element = dom.document.getElementById("scalajsShoutOut")

    val xhr = new XMLHttpRequest()
    xhr.open("GET",
      "http://127.0.0.1:9000"
    )
    xhr.onload = { (e: Event) =>
      element.innerHTML = s"以下是ajax请求来的数据\n${xhr.responseText}"
      jsNative("scala.js JS本地调用 => g.console.error(x)")
    }
    xhr.send()

    // 测试调用外部axios
    axios()
  }

  def jsNative(x: String): Unit = g.console.error(x)


  def axios(): Unit = {
    val dynamic = g.axios.get("http://127.0.0.1:9000")

    // 与JS无缝切换!
    val promise = dynamic.asInstanceOf[Promise[Any]]

    val future = promise.toFuture

    future.onComplete {
      case Success(value) => console.log("测试调用外部axios", value)
    }

  }
}

main.scala.html

手动添加axios库 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

@(title: String)(content: Html)

<!DOCTYPE html>

<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        @content
        @scalajs.html.scripts("client", routes.Assets.versioned(_).toString, name => getClass.getResource(s"/public/$name") != null)

    </body>
</html>



回帖