【问题标题】:d3.js / CoffeeScript: Access execution context (this) of both class and path in mouseoverd3.js / CoffeeScript:在鼠标悬停时访问类和路径的执行上下文(this)
【发布时间】:2013-07-09 20:56:03
【问题描述】:

我在 CoffeeScript 类中使用d3.js Streamgraph。我已经对其进行了调整,以便在鼠标悬停时路径的颜色会发生变化并出现工具提示。

现在我想将一些工具提示逻辑提取到一个单独的函数中。

我可以将执行上下文调整为一个或另一个,但不知道如何通过这两个:

class Graph

    render: ->
        ...
        dataArea.enter()
          .append("path")
              .on("mouseover", @onMouseOver)            # Option 1 - Pass path context
              .on("mouseover", @onMouseOver.bind(@))    # Option 2 - Pass class context

    onMouseOver: (data) ->
        d3.select(this).attr("class", "")   # 1.  Depends on path context (to adjust styling)
        @tooltipHelper(data)                # 2.  Depends on class context (which holds helper function)

    tooltipHelper: (data) ->
        ...

以前,我在similar question 上从@loganfsmyth 那里得到了一些关于点击事件的帮助。这将建议以下方面的答案:

.on("mouseover", (d) => @onMouseOver(d))

onMouseOver: (data) ->
  d3.select(data.target).attr("class", "")

不幸的是,这似乎不起作用。因此,这个问题的另一种表述方式可能是“鼠标悬停事件的 event.target 等价物是什么?”

来自@meetamit 的this answer 也与此相关。它建议通过将this(Graph 的实例)分配给在闭包外部声明的变量来解决这个问题,但我想这在 CoffeeScript 中是不可能的,因为这会将所有内容都放入闭包中。

你能帮忙吗?

【问题讨论】:

  • 你应该可以访问全局变量d3.event,如果我理解正确的话,它应该有你需要的所有信息。
  • @LarsKotthoff 这太完美了。我追求的是d3.event.currentTarget。如果您将其作为答案,我会接受。

标签: javascript coffeescript d3.js


【解决方案1】:

在这种情况下,您可以使用全局变量 d3.event 来访问您需要的所有信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多