Commit 39a7b6b2 authored by Administrator's avatar Administrator

Refactorizes the frontend

The frontend has been refactorized to use classes in the JavaScript files.
parent fa5608c2
function listPeople(done, fail, always) { var PeopleDAO = (function() {
var resourcePath = "rest/people/";
var requestByAjax = function(data, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {}; done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {}; fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {}; always = typeof always !== 'undefined' ? always : function() {};
$.ajax({ $.ajax(data)
url: 'rest/people',
type: 'GET'
})
.done(done) .done(done)
.fail(fail) .fail(fail)
.always(always); .always(always);
} };
function addPerson(person, done, fail, always) { function PeopleDAO() {
done = typeof done !== 'undefined' ? done : function() {}; this.listPeople = function(done, fail, always) {
fail = typeof fail !== 'undefined' ? fail : function() {}; requestByAjax({
always = typeof always !== 'undefined' ? always : function() {}; url: resourcePath,
type: 'GET'
}, done, fail, always);
};
$.ajax({ this.addPerson = function(person, done, fail, always) {
url: 'rest/people', requestByAjax({
url: resourcePath,
type: 'POST', type: 'POST',
data: person data: person
}) }, done, fail, always);
.done(done) };
.fail(fail)
.always(always);
}
function modifyPerson(person, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.ajax({ this.modifyPerson = function(person, done, fail, always) {
url: 'rest/people/' + person.id, requestByAjax({
url: resourcePath + person.id,
type: 'PUT', type: 'PUT',
data: person data: person
}) }, done, fail, always);
.done(done) };
.fail(fail)
.always(always);
}
function deletePerson(id, done, fail, always) { this.deletePerson = function(id, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {}; requestByAjax({
fail = typeof fail !== 'undefined' ? fail : function() {}; url: resourcePath + id,
always = typeof always !== 'undefined' ? always : function() {};
$.ajax({
url: 'rest/people/' + id,
type: 'DELETE', type: 'DELETE',
}) }, done, fail, always);
.done(done) };
.fail(fail) }
.always(always);
} return PeopleDAO;
\ No newline at end of file })();
\ No newline at end of file
var peopleFormId = 'people-form'; var PeopleView = (function() {
var peopleListId = 'people-list'; var dao;
var peopleFormQuery = '#' + peopleFormId;
var peopleListQuery = '#' + peopleListId;
function insertPeopleList(parent) { // Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self;
var formId = 'people-form';
var listId = 'people-list';
var formQuery = '#' + formId;
var listQuery = '#' + listId;
function PeopleView(peopleDao, formContainerId, listContainerId) {
dao = peopleDao;
self = this;
insertPeopleForm($('#' + formContainerId));
insertPeopleList($('#' + listContainerId));
this.init = function() {
dao.listPeople(function(people) {
$.each(people, function(key, person) {
appendToTable(person);
});
});
// La acción por defecto de enviar formulario (submit) se sobreescribe
// para que el envío sea a través de AJAX
$(formQuery).submit(function(event) {
var person = self.getPersonInForm();
if (self.isEditing()) {
dao.modifyPerson(person,
function(person) {
$('#person-' + person.id + ' td.name').text(person.name);
$('#person-' + person.id + ' td.surname').text(person.surname);
self.resetForm();
},
showErrorMessage,
self.enableForm
);
} else {
dao.addPerson(person,
function(person) {
appendToTable(person);
self.resetForm();
},
showErrorMessage,
self.enableForm
);
}
return false;
});
$('#btnClear').click(this.resetForm);
};
this.getPersonInForm = function() {
var form = $(formQuery);
return {
'id': form.find('input[name="id"]').val(),
'name': form.find('input[name="name"]').val(),
'surname': form.find('input[name="surname"]').val()
};
};
this.getPersonInRow = function(id) {
var row = $('#person-' + id);
if (row !== undefined) {
return {
'id': id,
'name': row.find('td.name').text(),
'surname': row.find('td.surname').text()
};
} else {
return undefined;
}
};
this.editPerson = function(id) {
var row = $('#person-' + id);
console.log(row);
if (row !== undefined) {
var form = $(formQuery);
console.log(form);
console.log(row.find('td.name').text());
console.log(row.find('td.surname').text());
form.find('input[name="id"]').val(id);
form.find('input[name="name"]').val(row.find('td.name').text());
form.find('input[name="surname"]').val(row.find('td.surname').text());
}
}
this.isEditing = function() {
return $(formQuery + ' input[name="id"]').val() != "";
};
this.disableForm = function() {
$(formQuery + ' input').prop('disabled', true);
};
this.enableForm = function() {
$(formQuery + ' input').prop('disabled', false);
};
this.resetForm = function() {
$(formQuery)[0].reset();
$(formQuery + ' input[name="id"]').val('');
$('#btnSubmit').val('Crear');
};
}
var insertPeopleList = function(parent) {
parent.append( parent.append(
'<table id="' + peopleListId + '">\ '<table id="' + listId + '">\
<tr>\ <tr>\
<th>Nombre</th>\ <th>Nombre</th>\
<th>Apellido</th>\ <th>Apellido</th>\
...@@ -14,11 +124,11 @@ function insertPeopleList(parent) { ...@@ -14,11 +124,11 @@ function insertPeopleList(parent) {
</tr>\ </tr>\
</table>' </table>'
); );
} }
function insertPeopleForm(parent) { var insertPeopleForm = function(parent) {
parent.append( parent.append(
'<form id="' + peopleFormId + '">\ '<form id="' + formId + '">\
<input name="id" type="hidden" value=""/>\ <input name="id" type="hidden" value=""/>\
<input name="name" type="text" value="" />\ <input name="name" type="text" value="" />\
<input name="surname" type="text" value=""/>\ <input name="surname" type="text" value=""/>\
...@@ -26,9 +136,9 @@ function insertPeopleForm(parent) { ...@@ -26,9 +136,9 @@ function insertPeopleForm(parent) {
<input id="btnClear" type="reset" value="Limpiar"/>\ <input id="btnClear" type="reset" value="Limpiar"/>\
</form>' </form>'
); );
} }
function createPersonRow(person) { var createPersonRow = function(person) {
return '<tr id="person-'+ person.id +'">\ return '<tr id="person-'+ person.id +'">\
<td class="name">' + person.name + '</td>\ <td class="name">' + person.name + '</td>\
<td class="surname">' + person.surname + '</td>\ <td class="surname">' + person.surname + '</td>\
...@@ -39,65 +149,21 @@ function createPersonRow(person) { ...@@ -39,65 +149,21 @@ function createPersonRow(person) {
<a class="delete" href="#">Delete</a>\ <a class="delete" href="#">Delete</a>\
</td>\ </td>\
</tr>'; </tr>';
} }
function formToPerson() {
var form = $(peopleFormQuery);
return {
'id': form.find('input[name="id"]').val(),
'name': form.find('input[name="name"]').val(),
'surname': form.find('input[name="surname"]').val()
};
}
function personToForm(person) {
var form = $(peopleFormQuery);
form.find('input[name="id"]').val(person.id);
form.find('input[name="name"]').val(person.name);
form.find('input[name="surname"]').val(person.surname);
}
function rowToPerson(id) {
var row = $('#person-' + id);
return {
'id': id,
'name': row.find('td.name').text(),
'surname': row.find('td.surname').text()
};
}
function isEditing() {
return $(peopleFormQuery + ' input[name="id"]').val() != "";
}
function disableForm() {
$(peopleFormQuery + ' input').prop('disabled', true);
}
function enableForm() {
$(peopleFormQuery + ' input').prop('disabled', false);
}
function resetForm() {
$(peopleFormQuery)[0].reset();
$(peopleFormQuery + ' input[name="id"]').val('');
$('#btnSubmit').val('Crear');
}
function showErrorMessage(jqxhr, textStatus, error) { var showErrorMessage = function(jqxhr, textStatus, error) {
alert(textStatus + ": " + error); alert(textStatus + ": " + error);
} }
function addRowListeners(person) { var addRowListeners = function(person) {
$('#person-' + person.id + ' a.edit').click(function() { $('#person-' + person.id + ' a.edit').click(function() {
personToForm(rowToPerson(person.id)); self.editPerson(person.id);
$('input#btnSubmit').val('Modificar'); $('input#btnSubmit').val('Modificar');
}); });
$('#person-' + person.id + ' a.delete').click(function() { $('#person-' + person.id + ' a.delete').click(function() {
if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) { if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) {
deletePerson(person.id, dao.deletePerson(person.id,
function() { function() {
$('tr#person-' + person.id).remove(); $('tr#person-' + person.id).remove();
}, },
...@@ -105,53 +171,13 @@ function addRowListeners(person) { ...@@ -105,53 +171,13 @@ function addRowListeners(person) {
); );
} }
}); });
} }
function appendToTable(person) { var appendToTable = function(person) {
$(peopleListQuery + ' > tbody:last') $(listQuery + ' > tbody:last')
.append(createPersonRow(person)); .append(createPersonRow(person));
addRowListeners(person); addRowListeners(person);
}
function initPeople() {
// getScript permite importar otro script. En este caso, se importan las
// funciones de acceso a datos.
$.getScript('js/dao/people.js', function() {
listPeople(function(people) {
$.each(people, function(key, person) {
appendToTable(person);
});
});
// La acción por defecto de enviar formulario (submit) se sobreescribe
// para que el envío sea a través de AJAX
$(peopleFormQuery).submit(function(event) {
var person = formToPerson();
if (isEditing()) {
modifyPerson(person,
function(person) {
$('#person-' + person.id + ' td.name').text(person.name);
$('#person-' + person.id + ' td.surname').text(person.surname);
resetForm();
},
showErrorMessage,
enableForm
);
} else {
addPerson(person,
function(person) {
appendToTable(person);
resetForm();
},
showErrorMessage,
enableForm
);
} }
return false; return PeopleView;
}); })();
$('#btnClear').click(resetForm);
});
};
...@@ -11,12 +11,13 @@ ...@@ -11,12 +11,13 @@
</div> </div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="js/dao/people.js"></script>
<script type="text/javascript" src="js/view/people.js"></script> <script type="text/javascript" src="js/view/people.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function() { $(document).ready(function() {
insertPeopleForm($('#people-container')); var view = new PeopleView(new PeopleDAO(), 'people-container', 'people-container');
insertPeopleList($('#people-container'));
initPeople(); view.init();
}); });
</script> </script>
</body> </body>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment