简体   繁体   English

为什么在更新 d3.js 强制布局时必须重新分配链接和节点

[英]Why do I have to re-assign the links and nodes when updating the d3.js force layout

In this example , where everybody leads me to, the code writer re-assigns the var link and node in the start() method.这个例子中,每个人都引导我,代码编写者在start()方法中重新分配 var linknode I don't really understand why.我真的不明白为什么。 Since both snipets are identical, I'll focus on one:由于两个片段是相同的,我将专注于一个片段:

link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
link.enter().insert("line", ".node").attr("class", "link");
link.exit().remove();

Q 1: link is already asigned as var link = svg.selectAll(".link"); Q 1: link已经被分配为var link = svg.selectAll(".link"); meaning link contains all DOM Elements in the svg container classed .link .意思是link包含.linksvg容器中的所有 DOM 元素。 This selection may be empty at the start of the example, but why does he re-asign it to all links in the force?这个选择在示例开始时可能是空的,但他为什么要将它重新分配给力中的所有链接?

Q 2: Why does he return the d.source.id and the d.target.id property? Q 2:为什么他返回d.source.idd.target.id属性? Is this necessary to identify the link?这是否有必要识别链接?

Q 3: Other manipulations (such as add color to a link) would be done like this?问题 3:其他操作(例如给链接添加颜色)会像这样完成吗?

link.enter().insert("line", ".node").attr("class", "link").style("stroke", function(d) { 
    return d.color;
});

Question 1:问题一:

Like you said initially its empty var link = svg.selectAll(".link");就像你最初说的,它的空var link = svg.selectAll(".link"); But when the data comes in the start function this variable holds all the current links.但是当数据进入start函数时,这个变量保存所有当前链接。

Question 2问题2

Q 2: Why does he return the d.source.id and the d.target.id property? Q 2:为什么他返回d.source.id和d.target.id属性? Is this necessary to identify the link?这是否有必要识别链接?

link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });

This is done to uniquely identify a link.这样做是为了唯一地标识一个链接。 The function returns a unique id of a link which is a combination of source and target id.该函数返回链接的唯一 ID,它是源 ID 和目标 ID 的组合。 Needed so that the exit function knows after intersection which link need to be removed.需要这样退出功能才能知道在相交后需要删除哪个链接。

Question 3问题三

Q 3: Other manipulations (such as add color to a link) would be done like this?问题 3:其他操作(例如给链接添加颜色)会像这样完成吗?

link.enter().insert("line", ".node").attr("class", "link").style("stroke", function(d) { 
    return d.color;
});

Yes.是的。 if the link data has a variable color in it.如果链接数据中有可变颜色。 Something like this {source: a, target: b, color:"red"} code here像这样{source: a, target: b, color:"red"}代码在这里

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM