Home > other >  How does a non existent class get executed with selectAll?
How does a non existent class get executed with selectAll?

Time:07-30

I am trying to learn d3.js.

Some tree plotting code has this css and the script part.

<style>
.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}
</style>

script part

// adds the links between the nodes
var link = g.selectAll(".link")
    .data( nodes.descendants().slice(1))
  .enter().append("path")
    .attr("class", "link")
    .style("stroke", function(d) { return d.data.level; })
    .attr("d", function(d) {
       return "M"   d.y   ","   d.x
           "C"   (d.y   d.parent.y) / 2   ","   d.x
           " "   (d.y   d.parent.y) / 2   ","   d.parent.x
           " "   d.parent.y   ","   d.parent.x;
       });

I see no link class mentioned in the body except in the script. Then how does the selectAll execute the .data method and remaining part as there are no elements with that class types?

CodePudding user response:

I suggest you read https://bost.ocks.org/mike/join/

svg.selectAll("circle")
  .data(data)
  .enter().append("circle")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", 2.5);

This code does exactly what you need: it creates a circle element for each data point, using the x and y data properties for positioning. But what’s with the selectAll("circle")? Why do you have to select elements that you know don’t exist in order to create new ones? WAT.

Here’s the deal. Instead of telling D3 how to do something, tell D3 what you want. You want the circle elements to correspond to data. You want one circle per datum. Instead of instructing D3 to create circles, then, tell D3 that the selection "circle" should correspond to data. This concept is called the data join:

  • Related