【问题标题】:Scala.js referencing using thisScala.js 使用 this 引用
【发布时间】:2016-12-06 02:07:47
【问题描述】:

我正在使用带有 Highcharts 外观的 scala.js (v0.6.13),我遇到了一个障碍,试图访​​问一些我通常会使用 'this' 和 'chart' 在 javascript 中访问的变量。这是一个例子:

咖啡脚本:

tooltip: {
  enabled: true,
  positioner: (labelWidth, labelHeight, point) ->
    return { x: chart.plotWidth - labelWidth + chart.plotLeft, y: 17 }
  formatter: () ->
    x = this.x
    point = this.points.find (p) -> x == p.x
    ...

我的问题是如何在 scala.js 的格式化程序和定位器函数中访问“this.x”和“chart.plotWidth”?到目前为止,这是我的 scala 代码:

override val tooltip: Cfg[Tooltip] = Tooltip(
  formatter = { () =>
    "what?"
  }: js.Function0[String],
  positioner = { (labelWidth: Any, labelHeight: Any, point: Object) =>
    js.Dynamic.literal(
      x = labelWidth,
      y = 17)
  }: js.Function3[Any, Any, Object, Object]
)

编辑:图表属于高图表。

【问题讨论】:

  • 您可能想指出您的原始 sn-p 是用 CoffeeScript 而不是 JavaScript 编写的,因此不熟悉 CoffeeScript 的 Scala.js 读者不会完全混淆。

标签: highcharts scala.js


【解决方案1】:

您需要使用js.ThisFunctionN 来显式捕获JavaScript 的特殊this 作为Scala.js 中的普通参数。

positioner = { (thiz: js.Dynamic, labelWidth: Any, labelHeight: Any, point: Object) =>
  // here the variable `thiz` holds what would be `this` in JS
  ...
}: js.ThisFunction3[js.Dynamic, Any, Any, Object, Object]

将 Scala 匿名函数转换为 js.ThisFunction 时,this 参数作为第一个参数传入。

请参阅https://www.scala-js.org/doc/interoperability/types.html 了解更多详情。

对于chart,您的问题没有提供足够的上下文来了解您的CoffeeScript 代码中的chart 是什么。但我想只要在 Scala.js 中使用 chart 就可以完成原始代码所做的任何事情。

【讨论】:

  • 感谢您的指导!
猜你喜欢
  • 2013-03-15
  • 1970-01-01
  • 2016-05-09
  • 2015-12-31
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
相关资源
最近更新 更多