Template d3 to add an item if missing

With D3, I find myself doing this a lot:

selectAll('foo').data(['foo']).enter().append('foo')

I would just add node if it does not exist yet, because I need to do updates in different places of the DOM tree, and the data that is convenient for me is not completely parallel to the DOM.

Is this a sign that I should reformulate my data so that it is parallel, or is there a less silly template that people use for this kind of "create if missing"?

+5
source share
1 answer

D3 implements the JOIN + INSERT / UPDATE / DELETE template, well known from the database world. In d3, you first select some DOM elements and then attach them to the data:

//join existing 'g.class' DOM elements with `data` elements
var join = d3.select('g.class').data(data)   

//get the join pairs that did not have 'g.class' join partner and
//INSERT new 'g.class' DOM elements into the "empty slots"
join.enter().append('g').attr('class', 'class')

//get the join pairs that did not have a `data` element as join partner and
//DELETE the existing 'g.class' DOM elements
join.exit().remove()

//get the join pairs that have a `data` element join partner and
//UPDATE the 'g.class' DOM elements
join.attr("name","value")

, , , . , . .

D3 . , treemap , treemap.nodes, , . treemap x,y,width,height . .

  • "" ,

"" , , , (, ), , / (, node ). .

+9

All Articles