I'm roughly familiar with how dragging works in d3. But I found something that flummoxed me recently.
Following through the code to create a force directed graph I can't follow the code to deal with dragging the nodes around:
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
Any idea why we're checking the if statement here in dragstarted and dragended?
I tried removing the if-condition and didn't really see much of a difference with the force directed graph. That is, instead of
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
I put
simulation.alphaTarget(0.3).restart();
and didn't see much of a difference.
The active
property is described here. It indicates how many drag events, other than the one the event is currently being fired for, are currently ongoing, and is only really relevant for multitouch scenarios. The reason this check is used is to keep the simulation going as long as there is at least one active drag occurring.
For example, if there are no active drags occurring, and you start dragging, in dragstarted
d3.event.active
will be 0, and the force simulation will start up. If d3.event.active !== 0
, then there is already a drag occurring and the simulation is already ongoing.
Likewise, in dragended
, if d3.event.active !== 0
, then another drag is still occurring and we don't want to stop the simulation. If d3.event.active === 0
, then this was the last drag and we want to stop the simulation.
(This answers OP's first question, not the new one regarding the if
condition)
I tried removing it and didn't really see much of a difference with the force directed graph.
Didn't you? The difference is quite big and very noticeable.
Without this line in the dragstarted
:
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
The simulation is not restarted when you drag a node. I made a bl.ocks copying Bostock's code and deleting that line only. Wait until the force stops (around 5 seconds) and try to drag a node:
https://bl.ocks.org/anonymous/7ad316f78d18233c1408d27c8ff58e0e
Did you see? You can't!
And, for this line in the dragended
:
if (!d3.event.active) simulation.alphaTarget(0);
Without it, the simulation never stops, it keeps slowly moving forever after you stop dragging the node. I made another bl.ocks copying Bostock's code and deleting that line only, try it:
https://bl.ocks.org/anonymous/6efa5edf188b3c87b7adbc877672b725
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With