Binding.scala使用教程5--监听变量变化

环境搭建查看 Binding.scala使用教程1–环境搭建, 主函数参考前面几篇文章

在这里插入图片描述

监听单一变量

package app
import com.thoughtworks.binding.dom
import com.thoughtworks.binding.Binding.{SingleMountPoint, Var}
import org.scalajs.dom.raw.Event


object View
{
  private val count = Var(0)

  private val count2=Var(0)

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

  val yourCustomMountPoint = new SingleMountPoint[Int ](count) {
    override def mount() = {
      super.mount()
      // Your custom initialization code
    }
    override def unmount() = {
      // Your custom clean up code
      super.unmount()
    }
    override protected def set(newValue: Int):Unit = {
      println("set mounted string",newValue)
      count2.value+=5
      // Your custom handler when `show` get changed
    }

  }

  @dom def render =
  {
    yourCustomMountPoint.bind
    <div>
      <h2>监听count的变化,然后改变count2</h2>
      <button onclick={addCount}>addCount</button>
      <p>count={count.bind.toString}</p>
      <p>count2={count2.bind.toString}</p>
    </div>
  }
}

监听数组

  • 初始界面界面

在这里插入图片描述

  • 控制台

在这里插入图片描述

  • 按下按钮后

在这里插入图片描述
在这里插入图片描述

View

package app

import com.thoughtworks.binding.dom
import com.thoughtworks.binding.Binding.{MultiMountPoint, SingleMountPoint, Var, Vars}
import org.scalajs.dom.raw.Event

import scala.collection.GenSeq


object View
{

  private val nums=Vars(1,2,3,4,5)

  val arrayChanged=new MultiMountPoint[Int](nums){

    override protected def set(children: Seq[Int]): Unit = {

      println("set")
    }

    override protected def splice(from: Int, that: GenSeq[Int], replaced: Int): Unit =
    {
      println("splice","from",from,"that",that,"replace",replaced)
    }
  }

  @dom def render =
  {
    arrayChanged.bind
    <div>
      <h2>监听数组的变化</h2>
      {
       for(num<-nums) yield <li>{num.toString}</li>
      }
      {
        <button onclick={ event: Event => nums.value += (10,11,12) }>-</button>
      }
    </div>
  }
}

猜你喜欢

转载自blog.csdn.net/qq_23989985/article/details/86665026
今日推荐