为什么Binding.scala路由器没有重新评估?

时间:2017-11-23 09:17:09

标签: scala routes scala.js binding.scala

我试图通过Binding.scala为个人项目构建通用路由器。

我已经定义了PageState特质

sealed trait WhistState {
  def text: String
  def hash: String

  def render: Binding[Node]
}

每个路由类型都有许多子类。然后我尝试创建一个路由器,基于哈希选择正确的类。

object Router {

  val defaultState: WhistState = DefaultState("Games")

  val allStates: Vector[WhistState] = Vector(defaultState)


  val route: Route.Hash[WhistState] = Route.Hash[WhistState](defaultState)(new Route.Format[WhistState] {

    override def unapply(hashText: String): Option[WhistState] = allStates.find(_.hash == window.location.hash)
    override def apply(state: WhistState): String = state.hash

  })

  route.watch()

}

然后我尝试使用此

我的应用程序类
object Application {
  import example.route.Router._

  @dom
  def render: Binding[Node] = {
    for (hash <- route.state.bind.hash) yield println("hash: " + hash)

    route.state.bind match {
      case default: WhistState => println("default"); default.render.bind
      case _                   => println("none");    <div>NotFound</div>
    }
  }

  def main(args: Array[String]): Unit = {
    dom.render(document.querySelector("#content"), render)
  }

}

我预计更改哈希会强制重新评估route.state.bind match ...表达式。

知道为什么这不起作用?

祝你好运

1 个答案:

答案 0 :(得分:1)

route.state仅在unapply返回Some(newState)并且newState不等于之前状态时更改。

在您的情况下,unapply始终会返回Some(defaultState)None。这就是为什么route.state永远不会改变的原因。