简体   繁体   中英

Reusable d3 charts with optional functionality

I encapsulated d3 charts into function as suggested best practice from creator in blog Towards Reusable Charts . Is it possible to create optional functionalities on top of this chart, so calling specific function would trigger it, otherwise it would be omitted.

Working JSFiddle example (base working example from Rob Moore's blog )

In JS line 56 I added a function which I'd like to create and then conditionally call in line 67.

My current way of doing it, is creating a boolean and setting it to false and then calling function with argument true . Problem of doing it this way is that the code gets too many conditionals and edge cases.

PS this question is not meant to be a discussion how to correctly apply axis to the chart. This is just an example.

I think it's better to add additional functionalities after the chart is drawn

var runningChart = barChart().barPadding(2).fillColor('coral');

d3.select('#runningHistory')
        .datum(milesRun)
        .call(runningChart);
        
runningChart.x_axis(); // additional functionality

So that the original chart container can be saved in a variable and it can be used to append other functionalities. For example

function barChart() {
  var charContainer;

    function chart(selection){

        charContainer = d3.select(this).append('svg')
                .attr('height', height)
                .attr('width', width);

    }

  chart.x_axis = function() {
     // Add scales to axis
    var x_axis = d3.axisBottom()
               .scale(widthScale);
    charContainer.append('g').call(x_axis);
    return chart;
  }
}

If there is any need to add additional functionality before the chart is drawn, then all the functionalities can be saved in a Javascript object and drawn like in this example. https://jsfiddle.net/10f7hdae/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM