D3.js v4 - Subselects

In d3.js v4, nested selections do not work as they were in the past.

This works (in version 3):

var data = [["1-a", "1-b"], ["2-a", "2-b"]];

var tbody = d3.select("tbody");

var row = tbody.selectAll("tr").data(data);
row.exit().remove();
row.enter().append("tr");

var cell = row.selectAll("td").data(function(d){ return d;});
cell.exit().remove();
cell.enter().append("td");
cell.text(function(d){ return d; });

https://jsfiddle.net/nwozjscs/

But not in v4: https://jsfiddle.net/nwozjscs/1/

I believe this has something to do with merge changes (...), but I could not find an example of the correct way to write nested selections in v4.

+4
source share
1 answer

I think I figured it out. It seems to work correctly if you combine the input and update the selection into one selection before joining the next data layer. Thus, any new data, as well as any existing data at the top level will be correctly taken into account at the next level down.

, . , v3, .

, !

https://jsfiddle.net/nwozjscs/2/

function render(data){
  var tbody = d3.select("tbody");

  var row = tbody.selectAll("tr").data(data);
  var rowenter = row.enter().append("tr");

  var cell = row.merge(rowenter)
    .selectAll("td").data(function(d){ return d;});

  cell.enter().append("td").text(function(d){ return d; });
}

render([["1-a", "1-b"], ["2-a", "2-b"]]);

setTimeout(function(){
    render([["1-a", "1-b", "1-c"], ["2-a", "2-b", "2-c"], ["3-a", "3-b", "3-c"]]);
}, 2000);
+2

Source: https://habr.com/ru/post/1656736/


All Articles