Binding.scala使用教程14--自定义全局路由

Home
package app

import com.thoughtworks.binding.dom

object Home
{
  @dom def render =
  {
    <p>i am the HomePage</p>
  }
}

Message
package app

import com.thoughtworks.binding.dom

object Message
{
  @dom def render =
  {
    <p>i am the MessagePage</p>
  }
}

Friend
package app

import com.thoughtworks.binding.dom

object Friend
{
  @dom def render =
  {
    <p>i am the FriendPage</p>
  }
}

Route

缺省值要写成这样 不然会导致返回类型不一致

case _ => <div></div>
package app

import com.thoughtworks.binding.Binding.{SingleMountPoint, Var}
import com.thoughtworks.binding.dom

object Route
{
  val path = Var("/home")
  @dom def render =
  {
    <div>
      {
        path.bind match
        {
          case "/home" => Home.render.bind
          case "/message" => Message.render.bind
          case "/friend" => Friend.render.bind
          case _ => <div></div>
        }
      }
    </div>
  }
}
View
package app

import com.thoughtworks.binding.Binding.{ Vars}
import com.thoughtworks.binding.dom

import org.scalajs.dom.raw.{Event}


object View
{
  private val activeCode = Vars.empty[String]

  private val array=Array.fill(3)("green item")

  activeCode.value++=array

  private def handleClick(index: Int,path:String) =
  {
    for (i <- 0 until activeCode.value.length)
    {
        if(index==i)
          activeCode.value(i)="active green item"
        else
          activeCode.value(i)="green item"
    }
    Route.path.value=path
  }

  @dom def render =
  {

    <div>
      <div class="ui pointing menu">
        <a class={activeCode.bind(0)} onclick={e: Event => handleClick(0,"/home")}>
        Home
        </a>
        <a class={activeCode.bind(1)} onclick={e: Event => handleClick(1,"/message")}>
        Message
        </a>
        <a class={activeCode.bind(2)} onclick={e: Event => handleClick(2,"/friend")}>
        Friend
        </a>
        <div class="right menu">
          <div class="item">
            <div class="ui transparent icon input">
              <input type="text" placeholder="Search..."/>
              <i class="search link icon"></i>
            </div>
          </div>
        </div>
    </div>
        <div class="ui segment">
        {Route.render.bind}
        </div>
    </div>
  }
}
MainApp
package app

import com.thoughtworks.binding.dom
import org.scalajs.dom.document

import scala.scalajs.js.JSApp

object MainApp extends JSApp
{
  def main(): Unit =
  {
    dom.render(document.body, View.render)
  }
}

防止IDEA 报错
import com.thoughtworks.binding.Binding

package object app
{
  implicit def makeIntellijHappy[T<:org.scalajs.dom.raw.Node](x: scala.xml.Node): Binding[T] =
    throw new AssertionError("This should never execute.")
}

相关文章:

  • 2022-12-23
  • 2021-10-20
  • 2021-08-12
  • 2022-01-07
  • 2021-07-20
  • 2021-10-18
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-04-15
  • 2021-09-09
  • 2021-12-14
  • 2021-05-15
  • 2022-12-23
  • 2021-08-08
  • 2021-09-24
相关资源
相似解决方案