我正在尝试使用ScalaJS显示高图图表。我可以使用文字表示法成功地做到这一点,
import org.scalajs.dom.{Event, document}
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => Lit}
object App {
def main(args: Array[String]): Unit = {
val dynamicOptions = Lit(
"chart" -> Lit(
"type" -> "bar"
),
"title" -> Lit(
"text" -> "Fruit Consumption"
),
"xAxis" -> Lit(
"categories" -> js.Array(
"Apples",
"Bananas",
"Oranges"
)
),
"yAxis" -> Lit(
"title" -> Lit(
"text" -> "Fruit eaten"
)
),
"series" -> js.Array(
Lit(
"name" -> "Jane",
"data" -> js.Array(1.0, 2.0, 4.0)
),
Lit(
"name" -> "John",
"data" -> js.Array(5.0, 7.0, 3.0)
)
)
)
document.addEventListener("DOMContentLoaded", (e: Event) => {
var chart = js.Dynamic.global.Highcharts.chart("highcharts", dynamicOptions)
})
}
}
然后我尝试在选项周围添加一些强类型:
import scala.scalajs.js
object Types {
class Chart(val `type`: String) extends js.Object
class Title(val text: String) extends js.Object
class XAxis(val categories: js.Array[String]) extends js.Object
class YAxis(val title: Title) extends js.Object
class DataPoint(
val name: String,
val data: js.Array[Double],
) extends js.Object
class Options(
val chart: Chart,
val title: Title,
val xAxis: XAxis,
val yAxis: YAxis,
val series: js.Array[DataPoint]
) extends js.Object
}
...
import org.scalajs.dom.{Event, document}
import scala.scalajs.js
object AppS {
import Types._
def main(args: Array[String]): Unit = {
val series = js.Array(
new DataPoint(
name = "Jane",
data = js.Array(1.0, 2.0, 4.0)
),
new DataPoint(
name = "John",
data = js.Array(5.0, 7.0, 3.0)
)
)
val staticOptions = new Options(
chart = new Chart("bar"),
title = new Title("Fruit Consumption"),
xAxis = new XAxis(js.Array(
"Apples", "Bananas", "Oranges"
)),
yAxis = new YAxis(new Title("Fruit eaten")),
series = series
)
document.addEventListener("DOMContentLoaded", (e: Event) => {
var chart = js.Dynamic.global.Highcharts.chart("highcharts", staticOptions)
})
}
}
这不起作用,因为出现奇怪的highchart错误。但是,如果我对动态和静态类型的对象进行字符串化并记录它们,它们是相同的。我该如何最好地使用与文字符号相同的强类型?