I'm looking for suggestions on how to clean up JavaScript/jQuery code that looks like the example in the Before
snippet.
I'm a backend developer so some of the constructs in JavaScript are foreign to me. I took a stab at it in the After
block but I'm not sure if there is a name for that design pattern.
Most of the JS code we have are click handlers and DOM table manipulation. There are also situations where we need to keep state like rows visible, etc.
In order to easily toggle console logging, I added a log()
function that checks the debug flag.
Before
$(function() {
// Delete button handler
$('.delete-button').click(function(e) {
e.preventDefault();
var id = $(this).closest('tr').data('id');
var name = $(this).prop('name');
var modal = $('#delete-modal');
modal.find('.modal-body').html("You've chosen to delete <strong>" + name + "</strong>");
modal.data('id', id);
modal.modal('show');
console.log('Showing modal');
});
// Confirm delete button handler
$('#confirm-delete-button').click(function(e) {
var modal = $('#delete-modal');
var id = modal.data('id');
modal.modal('hide');
console.log('Deleting id ' + id);
// Build form for submission
var $form = $('<form action="" method="POST"></form>');
$form.append('<input type="hidden" name="id" value="' + id + '">');
$form.append('<input type="hidden" name="reqType" value="Delete">');
$(document.body).append($form);
$($form).submit();
});
});
After
var App = {
rowCount: 0,
visibleCount: 0,
debug: true;
onReady: function () {
App.initHandlers();
},
log: function (message) {
if (App.debug) {
console.log(message);
}
},
initHandlers: function () {
$('.button-delete').click(App.showDeleteModal);
$('#button-confirm-delete').click(App.deleteRow);
},
showDeleteModal: function (event) {
event.preventDefault();
var id = $(this).closest('tr').data('id');
var name = $(this).prop('name');
var modal = $('#delete-modal');
modal.find('.modal-body').html("You've chosen to delete <strong>" + name + "</strong>");
modal.data('id', id);
modal.modal('show');
App.log('Showing modal');
},
deleteRow: function () {
var modal = $('#delete-modal');
var id = modal.data('id');
modal.modal('hide');
App.log('Deleting id ' + id);
// Build form for submission
var $form = $('<form action="" method="POST"></form>');
$form.append('<input type="hidden" name="id" value="' + id + '">');
$form.append('<input type="hidden" name="reqType" value="Delete">');
$(document.body).append($form);
$($form).submit();
},
updateToolbar: function () {
App.visibleCount = $('.product-row:visible').length;
App.rowCount = $('.product-row').length;
if (App.visibleCount === App.rowCount) {
$('div.toolbar').html('<h2><span class="label label-default">Showing ' + App.visibleCount + ' of ' + App.rowCount + ' rows</span></h2>');
} else {
$('div.toolbar').html('<h2><span class="label label-primary">Showing ' + App.visibleCount + ' of ' + App.rowCount + ' rows</span></h2>');
}
},
};
$(document).ready(App.onReady);