ramnathv / rCharts

Interactive JS Charts from R
http://rcharts.io
Other
1.19k stars 654 forks source link

Wrap chart generating code into a function #64

Open ramnathv opened 11 years ago

ramnathv commented 11 years ago

Here is the function from Rickshaw. I like to use chartId to identify elements of the chart so that multiple charts can be included on the same page. However, this is leading to a really ugly template. One way to resolve this is to encapsulate everything into a function and just call it with the right parameters.

<script type='text/javascript'> 
  var chartParams = {{{ chartParams }}}
  chartParams.element = document.querySelector('#{{{ chartId }}}')

  var graph{{{ chartId }}} = new Rickshaw.Graph(chartParams);

  graph{{{ chartId }}}.render();

  var x_axis = new Rickshaw.Graph.Axis.Time( { 
    graph: graph{{{ chartId }}} 
  } );

  {{# yAxis }}
  var yAxis = new Rickshaw.Graph.Axis.Y( {
    graph: graph{{{ chartId }}},
      orientation: '{{{ yAxis.orientation }}}',
      tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
      element: document.getElementById('yAxis{{{ chartId }}}'),
  });
  {{/ yAxis }}

  var hoverDetail{{{ chartId }}} = new Rickshaw.Graph.HoverDetail( {
    graph: graph{{{ chartId }}}
  });

  var legend{{{ chartId }}} = new Rickshaw.Graph.Legend( {
    graph: graph{{{ chartId }}},
    element: document.getElementById('legend{{{ chartId }}}')
  });

  var shelving{{{ chartId }}} = new Rickshaw.Graph.Behavior.Series.Toggle({
    graph: graph{{{ chartId }}},
    legend: legend{{{ chartId }}}
  });
</script> 
ramnathv commented 11 years ago

Here is one way I can rewrite this.

<script>
var chartParams = {{{ chartParams }}}, chartId={{{ chartId }}}, yAxis = {{{ yAxis }}}
function drawChart(chartParams, chartId, yAxis){
  chartParams.element = document.querySelector('#' + chartId)

  var graph = new Rickshaw.Graph(chartParams);
  graph.render();

  var x_axis = new Rickshaw.Graph.Axis.Time( { 
    graph: graph
  } );

  var yAxis = new Rickshaw.Graph.Axis.Y( {
    graph: graph,
      orientation: yAxis.orientation,
      tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
      element: document.getElementById('yAxis' + chartId),
  });

  var hoverDetail = new Rickshaw.Graph.HoverDetail( {
    graph: graph
  });

  var legend = new Rickshaw.Graph.Legend( {
    graph: graph,
    element: document.getElementById('legend'  + chartId)
  });

  var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
    graph: graph,
    legend: legend
  });
}
</script>