2
\$\begingroup\$

I'm new to JS and jQuery. I wrote this function which just does what I want, but it seems very unreadable, and because of my experience, I don't know a better way to handle it.

Could you please give advise me how to refactor it?

function new_section(id, name, order) {
 return $('<tbody>')
 .attr('id', 'section_' + id)
 .attr('data-id', id)
 .attr('data-order', order)
 .append($('<tr>')
 .addClass('head-row')
 .attr('id', 'section_' + id + '_head_row')
 .append($('<td>')
 .attr('id', 'section_' + id + '_name_cell')
 .attr('colspan', window.row_length)
 .text(name)
 .addClass('bg-info')
 .append($('<a>').addClass('edit-section').attr('href', '#')
 .append($('<i>').addClass('fa fa-pencil text-muted')))
 .append($('<span>').addClass('pipe-edit-section text-muted').text('|'))
 .append($('<a>').addClass('section-up').attr('href', '#')
 .append($('<i>').addClass('fa fa-chevron-up text-muted')))
 .append($('<a>').addClass('section-down').attr('href', '#')
 .append($('<i>').addClass('fa fa-chevron-down text-muted')))
 .append($('<span>').addClass('pipe-edit-section text-muted').text('|'))
 .append($('<a>').addClass('delete-section').attr('href', '#')
 .append($('<i>').addClass('fa fa-times-circle text-muted')))
 )
 );
}

UPD:

Found underscore templates. What do you think about this approach:

section = _.template([
 '<tbody id="section_<%= id %>" data-id="<%= id %>" data-order="<%= order %>">',
 '<tr id="section_<%= id %>_head_row" class="head-row">',
 '<td id="section_<%= id %>_name_cell" class="bg-info" colspan="<%= row_length %>">',
 '<%= name %>',
 '<a href="#" class="edit-section">',
 '<i class="fa fa-pencil text-muted"></i>',
 '</a>',
 '<span class="pipe-edit-section text-muted">|</span>',
 '<a href="#" class="section-up">',
 '<i class="fa fa-chevron-up text-muted"></i>',
 '</a>',
 '<a href="#" class="section-down">',
 '<i class="fa fa-chevron-down text-muted"></i>',
 '</a>',
 '<span class="pipe-edit-section text-muted">|</span>',
 '<a href="#" class="delete-section">',
 '<i class="fa fa-times-circle text-muted"></i>',
 '</a>',
 '</td>',
 '</tbody>'].join('\n'));
Alex L
5,7832 gold badges26 silver badges69 bronze badges
asked Jan 1, 2015 at 20:56
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

There isn't much to refactor here and you already identified the problem scope.

You are much better off with a JavaScript template engine.

I won't be too opinionated here, but popular options are:

answered Jan 6, 2015 at 21:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.