d3 pattern to add an element if missing

后端 未结 1 631
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 12:00

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

相关标签:
1条回答
  • 2020-12-29 12:22

    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.

    0 讨论(0)
提交回复
热议问题