将数据传递给d3.js中的.call

Passing data to .call in d3.js

本文关键字:js 中的 call d3 数据      更新时间:2023-09-26

此实验基于Health&国富的例子。我试图让一个工具提示样式的标签显示出来,并在鼠标悬停在每个点上时浮动在它们上面。每个数据元素都有一个名为"name"的属性,我想在工具提示中显示它。为了简洁起见,我省略了大部分不相关的代码。

// Create all the dots, one for each data point.
var dot = svg.append("g")
    .attr("class", "dots")
  .selectAll(".dot")
    .data(myData)
  .enter().append("circle")
    .attr("class", "dot")
    .call(position)
    .call(enableInteraction)
    .sort(order);
// Create a tooltip element.
var tooltip = svg.append("text")
    .attr("class", "tooltip");
// Assign each of the dots the various mouse events.
function enableInteraction(dot) {
  dot.on("mouseover", mouseover)
     .on("mouseout", mouseout)
     .on("mousemove", mousemove);
  function mouseover() {
    tooltip.text(???); // How do I get the name into here?
  }
  function mouseout() {
    tooltip.text("");
  }
  function mousemove() {
    var cursor = d3.mouse(this);
    tooltip.attr("x", cursor[0] + 5)
           .attr("y", cursor[1] + 5);
  }
}

我尝试使用一个函数来检索名称,并将其传递到enableInteraction()中,如下所示:

.call(enableInteraction, function(d) { return d.name; } )

但是传递的是函数对象,而不是它的返回值。

那么,如何在工具提示中显示每个数据元素的名称呢?

您可以使用currying技术将该信息获取到鼠标悬停事件处理程序中。我不确定获取名称的语法,但这是一个想法:

// this function returns a function
function moveoverHandler(dot) {
    return function mouseover() {
        // I'm not sure if this is how you get the "name" property from the "dot" object 
        // Please update this as needed
        var name = dot.data("name");  
        tooltip.text(name);  
    }
}

然后像这样连接处理程序:

dot.on("mouseover", mouseover(dot));