Я новичок в d3 и все еще учусь. У меня есть узел и ссылка в качестве переменных в d3, которые выбирают соответствующие узлы и ссылки из заданного json формата данных / графика , Я написал функцию для изменения цвета каждой ссылки на основе источника и target name.
Что я не мог понять, так это то, что вызов этой функции для переменной node также меняет цвет ссылок. Так имеет ли значение какой объект я вызываю? Изменяется ли внутренняя переменная 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)');
});
}