1

我的应用程序中有一个地理坐标列表,存储在Vars[Coordinates]. 我现在想在地图上显示这些,并在将新坐标添加到列表中或从列表中删除时自动更新地图。我正在使用一个库来公开 API 以在地图上添加和删除标记,所以我想在列表更新时调用这些,但我找不到任何明显的方法来做到这一点。关于如何实现这一目标的任何提示?

编辑:感谢@杨波的回复!我最终得到了这样的结果:

val coordinates = Vars.empty[Coordinates]
def mapMountPoint(parent: Element, coordinates: BindingSeq[Coordinates]) =
  new MultiMountPoint[Coordinates](coordinates) {
    … // method overrides here to create the map in parent
  }
@dom 
def map = {
  val e = <div></div>
  mapMountPoint(e, coordinates).bind
  e
}

它似乎工作,当 div 被渲染或从 DOM 中删除时调用 mount 和 unmount 方法……但这真的是应该这样做的吗?它看起来有点奇怪,而且我在调用.bind:的地方也收到了编译器警告a pure expression does nothing in statement position; multiline expressions might require enclosing parentheses

在 monadic-html 库中,有一种相当优雅的方法:

<canvas mhtml-onmount={ e => crazyCanvasStuff(e) }></canvas>

还有一个匹配的 mhtml-onunmount 属性用于清理。

4

2 回答 2

1

您可能想要创建自己的MultiMountPoint,它会覆盖spliceset方法。

然后将你的挂载点注入到渲染过程中,类似于https://stackoverflow.com/a/45101054/955091


与 Haskell 不同,您可以在任何地方在 Scala 中执行副作用,甚至在 HTML 模板中。如果你写了类似的东西<canvas id="my_canvas" data:dummy_attribute={ crazyCanvasStuff(my_canvas, coordinates.all.bind); "dummy_value" }></canvas>,它也应该可以工作。

但是,不推荐执行副作用的其他解决方案,因为它们的行为取决于 Binding.scala 的内部实现。例如,当 Binding.scala 运行时发现上游数据未更改(Binding.scala 路由器)时,可能不会重新评估副作用。使用挂载点是执行副作用的唯一正确方法,尤其是当您需要部分更新或想要管理在渲染期间创建的自定义对象的生命周期时。

于 2018-02-26T07:00:33.193 回答
-1

我使用 https://github.com/rtimush/scalatags-rx

build.sbt: libraryDependencies += "com.timushev" %%% "scalatags-rx" % "0.3.0"

示例:按下按钮时的机会颜色,使用 scalatags ...

var colorActiv = "green"
var colorInActiv = "black"

val buttonDateColor = Var(colorInActiv) // big V in Var
val buttonDateRx = Rx(buttonDateColor())

...

def buttonDateOnclick(): Unit = {
    if (buttonDateColor.now == colorInActiv){
        buttonDateColor() = colorActiv
    } else {
        buttonDateColor() = colorInActiv
    }
}

... // 在 Menubuttons 对象中:

var menuButtons =
div(
    button(
        menubuttonClass,
        color := buttonDateRx,
        onclick := buttonDateOnclick _,
        "button-text"
    )

...在主/初始化()中:

dom.document.getElementById("buttonsdiv").appendChild(Menubuttons.menuButtons.render)
于 2018-03-06T15:48:48.943 回答