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?
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:
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 allx,y,width,heightvalues 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
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.