d3.js - d3 adding data attribute conditionally -


i'm creating table d3 used footable jquery plugin , requires having data- attributes in header row. not columns have data attributes , wondering if there way this.

this approach sort of works, adding possible data attributes , leaving blank, i'm sure it's not practise.

var th = d3.select(selection).select("thead").selectall("th")             .data(colspec)             .enter().append("th")             .text(function(d) { return d["data-name"]; })             .attr("data-class", function(d) {                 if ("data-class" in d) {                     return d["data-class"];                 } else {                     return "";                 }             })             .attr("data-hide", function(d) {                 if ("data-hide" in d) {                     return d["data-hide"];                 } else {                     return "";                 }             })             .attr("data-ignore", function(d) {                 if ("data-ignore" in d) {                     return d["data-ignore"];                 } else {                     return "";                 }             })         etc. 

colspec example:

[{"data-name": "username"}, {"data-name": "date joined", "data-hide": "true"}] 

currently getting:

  <th data-class="" data-hide="true" data-ignore="" data-type="">joined</th> 

want

   <th  data-hide="true" >joined</th> 

any suggestions?

seems candidate .each():

var th = d3.select(selection).select("thead").selectall("th")         .data(colspec)     .enter().append("th")         .text(function(d) { return d["data-name"]; })         // address each item individually         .each(function(d) {             var header = d3.select(this);             // loop through keys - assumes no data             d3.keys(d).foreach(function(key) {                 if (key != "data-name")                     header.attr(key, d[key]);             });         }); 

i use .each when having per-item scope makes more sense trying figure out bunch of attributes each item.

for short list of attributes, if you're worried data in objects, it's easier loop through desired keys instead of everything:

        .each(function(d) {             var header = d3.select(this);             ['data-class', 'data-hide', 'data-ignore'].foreach(function(key) {                 if (key in d)                     header.attr(key, d[key]);             });         }); 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -