Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 pattern to add an element if missing

Tags:

d3.js

With D3, I'm finding myself doing this a lot:

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

I'd like to simply add a node if it doesn't already exist, because I need to do updates at different places in the DOM tree, and the data I have handy isn't exactly 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 pattern that folks use for this kind of 'create if missing' thing?

like image 532
joel truher Avatar asked Jan 23 '13 03:01

joel truher


1 Answers

D3 implements a JOIN + INSERT/UPDATE/DELETE pattern well known from the DB world. In d3 you first select some DOM elements and then join it with 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")

You see, if you have data that nicely fits your UI requirements you can write very maintainable code. If you try hacks outside this pattern, your UI code will make you very sad soon. You should preprocess your data to fit the needs of the UI.

D3 provides some preprocessors for some use cases. For example the treemap layout function flattens a hierarchical data set to a list treemap.nodes, which you can then use as simple list-based data set to draw a rectangle for each element. The treemap layout also computes all x,y,width,height values for you. You just draw the rects and do not care about the hierarchy anymore.

In the same way you can develop your own helper functions to

  1. convert your data to a better consumable format and
  2. try to enrich the data with "hints" for the UI, how to draw it

These "hints" may comprise geometry values, label texts, colors, and basically everything that you cannot directly derive from looking at a single data element (such as the treemap geometry), and that would require you to correlate each element with some/all other elements (e.g., determining the nesting depth of a node in a tree). Doing such a tasks in one preprocessing step allows you write cleaner and faster code for that task and separates the data processing from the drawing of the UI.

like image 75
Juve Avatar answered Dec 02 '22 03:12

Juve