Reputation: 2085
I need to implement something similar to this, so I am trying to understand this code.
There are certain things which I am having a tough time to understand. For instance, in the code below, path.attr("d", linkArc);
seems to be calling the linkArc
function. However, linkArc
function expects a parameter, which is not passed. Still it manages to get an Object called d
. What object is this and how is it getting passed? What does d
in path.attr
signify?
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", linkArc); //<- this line
circle.attr("transform", transform);
text.attr("transform", transform);
}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
Can someone please help me understand this?
Upvotes: 0
Views: 212
Reputation: 2238
This is how the .attr() operator works:
Quote from the d3 documentation (https://github.com/mbostock/d3/wiki/Selections#attr):
selection.attr(name[, value])
If value is specified, sets the attribute with the specified name to the specified value on all selected elements. If value is a constant, then all elements are given the same attribute value; otherwise, if value is a function, then the function is evaluated for each selected element (in order), being passed the current datum d and the current index i, with the this context as the current DOM element. The function's return value is then used to set each element's attribute. A null value will remove the specified attribute.
Basically it means you can use the function like this:
function linkArc(d, i) {
// 'd' is the datum
// 'i' is the index
// 'this' will be the current DOM element
}
Upvotes: 3
Reputation: 3177
From the d3 docs:
selection.attr(name[, value])
...if value is a function, then the function is evaluated for each selected element (in order), being passed the current datum
d
and the current indexi
, with the this context as the current DOM element. The function's return value is then used to set each element's attribute. A null value will remove the specified attribute...
That's where the d
is coming from. It's the selection
Objects currently set d
(datum).
A nice illustration of this in action is if you also add i
to the linkArc()
function:
function linkArc(d,i) {
console.log('d: ' + d + ' || i: ' + i);
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
And a Fiddle
Upvotes: 3