Binding.scala使用教程9--binding.scala使用JQuery进阶

提要

  • 前面一篇博客写道了关于如何在Binding.scala中使用semantic UI, 这个UI 框架中需要用到JQuery,但在使用JQuery中会出现一些问题,比如只是在Binding.scala中的 @dom中 调用了JQuery的方法,页面不会生效,为了解决这个问题,需要在页面初始化的时候在主函数的 dom.render() 后面调用一次JQuery方法。查看下面的例子

效果图和目录结构

Binding.scala使用教程9--binding.scala使用JQuery进阶

View
package app
import com.thoughtworks.binding.dom
import com.thoughtworks.binding.Binding.{SingleMountPoint, Var}
import org.scalajs.dom.raw.Event
import SemanticUI.jq2semantic
import org.scalajs.dom.html.Input
import org.querki.jquery.$

import scala.scalajs.js.Dynamic.literal


object View
{
  private val count = Var(25)

  private val input = Var("")

  val addCount =
  {
    event: Event =>
      count.value += 1
      progress

  }
  val subCount =
  {
    event: Event =>
      count.value -= 1
      progress
  }

  def progress=$("#example1").progress(literal(percent = count.value))

  def dropdown= $(".ui.dropdown").dropdown(literal(on="hover",clearable= true))

  def mounted(): Unit =
  {
    progress
    dropdown
  }

  
  @dom def render =
  {
    <div>
      <div class="ui indicating progress" data:data-percent={count.bind.toString} id="example1">
      <div class="bar"></div>
      </div>
      <button class="tiny ui positive basic button" onclick={addCount}>+</button>
      <button class="tiny ui positive basic button" onclick={subCount}>-</button>
      <p>{count.bind.toString}</p>

       <div class="ui selection dropdown">
        <input type="hidden" name="gender"  onchange={ event: Event => input.value= event.currentTarget.asInstanceOf[Input].value }/>
        <i class="dropdown icon"></i>
        <div class="default text">Gender</div>
        <div class="menu">
          <div class="item" data:data-value="Male">Male</div>
          <div class="item" data:data-value="Female">Female</div>
        </div>
      </div>
      the selected value is { input.bind }
    </div>
  }

}
SemanticUI

这里面添加隐式转换

package app

import scala.scalajs.js
import org.querki.jquery.JQuery


// SemanticUI 的隐式转换
object SemanticUI
{
  @js.native
  trait SemanticJQuery extends JQuery {
    def dropdown(params: js.Any*): SemanticJQuery = js.native
    def progress(params: js.Any*): SemanticJQuery = js.native
  }
  implicit def jq2semantic(jq: JQuery): SemanticJQuery = jq.asInstanceOf[SemanticJQuery]
}

MainApp

View.mounted() 做初始化

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)
    View.mounted()
  }
}

package object
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.")
}