d3 adding data attribute conditionally

后端 未结 5 1395
悲&欢浪女
悲&欢浪女 2021-02-01 14:01

I\'m creating a table with d3 to be used by the FooTable jquery plugin and this requires having some data- attributes in the header row. But not all columns have all the data a

5条回答
  •  时光取名叫无心
    2021-02-01 14:34

    The most voted solution is perfect because .attr(a,b) works as conditional when b is null,

     d3chain.attr('data-class', d=>'data-class' in d ? d['data-class'] : null );
    

    but this solution is not geral, is not valid for other chaining methods, except using .each(), .filter or .call(). In general the most simple is call().

    .call(condFunc,param)

    Suppose that param is an global variable used as parameter in the condition, and that g is a global object used to return a value.

      // inconditional
      d3chain.attr(param, g[param])
    
      // conditional case using globals
      d3chain.call( s => { if (g[param]) s.attr(param,g[param]) })
    
      // conditional case passing the parameter
      d3chain.call( (s,p) => {
         if (g[p]) s.attr(p, g[p])
      }, param)
    

    .each(d => condFunc)

    Typical use:

     d3chain.each( d=> {
         if (param && d) d3.select(this).attr(d, g[param])
     })
    

    See @nrabinowitz answer for detailed example.

    .filter(d=>condFunc).etc

    Typical use:

     d3chain.filter( d=> param in d ).attr(param, d=> g[param])
    

    See @LarsKotthoff answer for detailed example.

提交回复
热议问题