D3 - 了解 d3 call() 方法的调用对象



我是d3的新手,还在学习。 我在 d3 中有节点链接作为变量,从给定的 json 数据格式/graph 中选择相应的节点和链接。 我编写了一个函数,根据其目标名称更改每个链接的颜色。

我无法理解的是,在变量节点上调用此函数也会更改链接的颜色。那么我在什么对象上调用这个函数甚至重要吗?d变量是否根据我调用函数的内容从节点内部更改为链接?

法典

//How link is defined
var link=svg
.append("g")
.selectAll("line")
.data(graph.links)
.enter()
.append("line")
.attr("stroke-width",function(d){
return 3
})
.style("stroke","pink")
.text("text",function(d){return d.name});
//How node is defined
var node =svg
.append("g")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r",5)
.attr("fill", function(d){
return "orange"
})
.attr("stroke","yellow")
;
//link.call(updateState1)
//This works as it should
node.call(updateState1)
// I can't understand why this line works too.
function updateState1() {
link
.each(function(d) {
var colors=["red","green","blue"]
var num=0;
if(d.source.name.length>d.target.name.length)
{
num=1;
console.log("Inside 1");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else if(d.source.name.length<d.target.name.length)
{
num=2;
console.log("Inside 2");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else{
num=0;
}
// your update code here as it was in your example
d3
.select(this)
.style("stroke", function(d){ return colors[num]})
.attr('marker-end','url(#arrowhead)');



});

}

当你使用selection.call函数的第一个参数是调用它selection。所以如果你看一下:

function updateState1() {
link
.each(function(d) {

您可以看到您正在显式使用link,这就是链接更新的原因。相反,如果将其更改为:

function updateState1(selection) {
selection
.each(function(d) {

它应该使用selection.call中的选择(在node.call(updateState1)的情况下node(。

如果你传递给selection.call的函数不接受任何参数,则相当于只调用函数本身(即,如果fn没有任何参数selection.call(fn)fn()相同(。

最新更新