如何在使用 Binding.scala 将元素加载到 dom 后执行一些初始化

How to execute some init after element loaded to dom with Binding.scala

@dom 
def chart(show: Var[Boolean]) = {
  if(show.bind) {
    <canvas id="chartCanvas"><canvas>
  }
}

当 canvas 加载到 dom 时,如何使用 chartjs 等图表库初始化它?

解决方案 1

@dom 
def chart(show: Var[Boolean]) = {
  if(show.bind) {
    val myCanvas = <canvas id="chartCanvas"><canvas>
    myInitializationCode(myCanvas)
    myCanvas
  } else {
    <!-- don't show canvas -->
  }
}

解决方案 2

您可以创建自定义 SingleMountPoint,并将初始化代码放在覆盖的 mount 方法中:

val yourCustomMountPoint = new SingleMountPoint[Boolean](show) {
  override def mount() = {
    super.mount()
    // Your custom initialization code
  }
  override def unmount() = {
    // Your custom clean up code
    super.unmount()
  }
  override def set(newValue: Boolean) = {
    // Your custom handler when `show` get changed
  }
}

// Inject your custom mount point into the rendering process
yourCustomMountPoint.bind