[英]Passing data to .call in d3.js
This experiment is based on the Health & Wealth of Nations example. 该实验基于健康与财富国家的例子。 I'm trying to have a tooltip-style label show up and float above each of the dots when the mouse hovers over them. 当鼠标悬停在每个点上时,我正试图显示工具提示样式的标签并漂浮在每个点上方。 Each data element has a property called "name" that I'd like to display in the tooltip. 每个数据元素都有一个名为“name”的属性,我想在工具提示中显示。 For the sake of brevity I omitted most of the irrelevant code. 为简洁起见,我省略了大部分不相关的代码。
// 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);
}
}
I tried using a function to retrieve the name and pass it into enableInteraction() as follows: 我尝试使用函数来检索名称并将其传递给enableInteraction(),如下所示:
.call(enableInteraction, function(d) { return d.name; } )
but the function object is being passed instead of its return value. 但正在传递函数对象而不是其返回值。
So how do I get each data element's name to display in the tooltip? 那么如何让每个数据元素的名称显示在工具提示中?
You could use a currying technique to get that info into your mouseover event handler. 您可以使用currying技术将该信息输入mouseover事件处理程序。 I'm unsure of the syntax for getting the name, but this is the idea: 我不确定获取名称的语法,但这是个主意:
// 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);
}
}
Then wire up the handler like this: 然后像这样连接处理程序:
dot.on("mouseover", mouseover(dot));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.