Scala.js:如何使用 Scala.js 读取输入元素的值?

Scala.js: How do I read the value using of an input element using Scala.js?

我正在尝试做这样的事情:

<input id="test">Hello!</input>

import io.udash.wrappers.jquery.jQ

// Read from Scala
val x = jQ("#test").value().asIntanceOf[String]

但是,我得到一个 ClassCastException 说 String | Int | Double | js.Array[Any] 不能转换为 String

我想出了一个类型类方法(它隐藏了丑陋的东西asInstanceOf):

import scala.scalajs.js.|
import scala.util.Try

trait JsRead[A] { self =>
  import JsRead.Or
  def apply(value: Or): Option[A]

  def map[B](f: A => Option[B]): JsRead[B] = new JsRead[B] {
    override def apply(value: Or) = self.apply(value).flatMap(f)
  }
}

object JsRead {
  type Or = _ | _

  def apply[A](f: Or => Option[A]): JsRead[A] = new JsRead[A] {
    override def apply(value: Or) = f(value)
  }

  implicit class Dsl(value: Or) {
    def as[A](implicit reader: JsRead[A]): Option[A] =
      reader(value)
  }

  implicit val string: JsRead[String] = JsRead(x => Try(x.asInstanceOf[String]).toOption)
  implicit val int: JsRead[Int]       = string.map(_.toIntOption)
  implicit val double: JsRead[Double] = string.map(_.toDoubleOption)
}

现在我可以将其用作:

import io.udash.wrappers.jquery.{jQ => $}

for {
  deposit           <- $("#deposit").value().as[Int]
  monthlyWithdrawal <- $("#monthlyWithdrawal").value().as[Int]
  irr               <- $("#irr").value().as[Double]
  inflation         <- $("#inflation").value().as[Double]
  year              <- $("#year").value().as[Int]
} {
  // do something
}