Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Created October 20, 2017 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shinpeim/3b80a45eeba465b322be5da9503e52bc to your computer and use it in GitHub Desktop.
Save Shinpeim/3b80a45eeba465b322be5da9503e52bc to your computer and use it in GitHub Desktop.
js側が要求するインターフェースに合致したcase classをjs側に渡す方法
// JS側はこういうインターフェースになってるとする
exports.nyan = function({a, b}){
console.log(a);
console.log(b);
}
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExportAll, JSImport}
// js側が要求する引数の型をtraitで定義して
@js.native
trait ArgNative extends js.Object{
val a: String = js.native
val b: Int = js.native
}
// JSファイルをimport
@js.native
@JSImport("./nyan.js", JSImport.Namespace)
object NyanJS extends js.Object{
def nyan(args: ArgNative): Unit = js.native
}
// js側が要求する型に合わせてScala側から触るcase classを用意して
@JSExportAll
case class Arg(a: String, b: Int)
object Main {
def main(args: Array[String]): Unit = {
// scalaからは普通にArgをcaseClassとして使って
val arg = Arg("hey", 1)
// こうやってjs側のオブジェクトにキャストして
val argNative = js.use(arg).as[ArgNative]
// JSのモジュールに渡す
NyanJS.nyan(argNative)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment