页面上有多个NVD3图表.如何简化javascript代码和包装函数

Multiple NVD3 charts on page. How to simplify the javascript code and wrap function?

本文关键字:javascript 何简化 代码 函数 包装 图表 NVD3      更新时间:2023-09-26

我目前在网站上使用NVD3来绘制图表,其中一个页面有6个图表。目前,我为这6个图分别添加了6个函数,但我觉得这不是最优雅的解决问题的方法。下面是相关html/javascript代码的示例:

<div id="chicago" class='with-3d-shadow with-transitions chart'>
  <svg> </svg>
</div>
nv.addGraph(function() {
  var chicago = nv.models.lineChart()
      .margin({top: 30, right: 60, bottom: 50, left: 80})
      .x(function(d,i) { return i })
      .color(d3.scale.category10().range());
  chicago.transitionDuration(500);
  chicago.xAxis.tickFormat(function(d) {
      var dx = testdata[0].values[d] && testdata[0].values[d].x || 0;
      if (dx > 0) {
          return d3.time.format('%x')(new Date(dx))
      }
      return null;
  });
  chicago.yAxis
      .axisLabel('Price ($/Dth)')
      .tickFormat(function(d) { return '$' + d3.format(',.2f')(d) });
  nv.log(testdata);
  d3.select('#chicago svg')
      .datum(testdata)
      .call(chicago);
  nv.utils.windowResize(chicago.update);
  return chicago;
});

我该如何包装该函数,以便我可以多次重用它,而不必重复它并替换每个图形的名称(在本例中为'chicago') ?

这很简单,这是一种方法。

HTML:

<div id='chart1'>
    <h3>My Chart 1</h3>
    <svg></svg>
</div>
<div id='chart2'>
    <h3>My Chart 2</h3>
    <svg></svg>
</div>
<div id='chart3'>
    <h3>My Chart 3</h3>
    <svg></svg>
</div>
JavaScript:

// Call my charts , pass in my div id here
drawChart('chart1');
drawChart('chart2');
drawChart('chart3');
//Donut chart example
function drawChart(div) {
    var width = height = 400;
    
    nv.addGraph(function () {
        var chart = nv.models.pieChart()
            .x(function (d) {
            return d.label
        }).y(function (d) {
            return d.value
        }).width(width)
          .height(height)
          .showLabels(true)
          .labelThreshold(.05)
          .labelType("percent")
          .donut(true);
        d3.select("#" + div + " svg")
            .datum(exampleData())
            .attr('width', width).attr('height', height)
            .transition().duration(350)
            .call(chart);
        return chart;
    });
}