Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This function is meant to take an object, loop through the key-values and generate/build a HTML table at a particular ID:

function insertBasicTable(basic_data, insert_id) {
  /* Insert the key/value pairs into a table element on the DOM.

  basic_data = object containing key/value pairs
  insert_id  = the id on the DOM to insert the table into 

  Intentionally not including closing tags in the jquery requests;
  http://stackoverflow.com/a/14737115/2355035 */

  table_id = '#' + insert_id;
  var array_length = Object.keys(basic_data).length;
  var array_obj_names = Object.keys(basic_data);

  // create the table header
  $(table_id).empty();
  $(table_id).append('<thead>');
  $(table_id).find('thead:last').append('<th>Tag');
  $(table_id).find('thead:last').append('<th>Data');

  // begin the table body and iterate through key/value pairs
  $(table_id).append('<tbody>');
  for (var i = 0; i < array_length; i++) {
    var attr_name = array_obj_names[i];
    var tag       = '<td>' + array_obj_names[i];
    var data      = '<td>' + basic_data[attr_name];

    $(table_id).find('tbody:last').append('<tr>' + tag + data);
  }
}

This function is then used, along with a number of D3 scripts, to populate elements on the DOM:

linePlot.render(someObject.modules.qual.quintiles);
boxPlot.render(someObject.modules.qual.quintiles);
insertBasicTable(someObject.modules.basic, 'basic-stats-table');
// etc, etc...

Any comments about how this is being achieved? Am I overlooking either a basic tenant of how JS "should" be used (this is a huge side-effect for instance, should I be returning a formatted string then placing that string into the DOM for instance) or over-complicating things by jQuery'ing a bunch of times?

share|improve this question

1 Answer 1

You should cache $table and $tbody, instead of re-instantiating them every time you need them.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.