var PetsView = (function() {
var dao;
// Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self;
var formId = 'pets-form';
var listId = 'pets-list';
var formQuery = '#' + formId;
var listQuery = '#' + listId;
function PetsView(petsDao, formContainerId, listContainerId) {
dao = petsDao;
self = this;
insertPetsForm($('#' + formContainerId));
insertPetsList($('#' + listContainerId));
this.init = function() {
$('#' + formContainerId).before('
Mascotas
');
var daoPeople = new PeopleDAO();
dao.listPets(function(pets) {
$.each(pets, function(key, pet) {
daoPeople.getPeople(pet.idOwner,
function(person) {
appendToTable(pet, person);
},
showErrorMessage
);
});
});
daoPeople.listPeople(function(people) {
$.each(people, function(key, person) {
appendToFormSelect(person);
});
},
function() {
alert('No ha sido posible acceder al listado de personas.');
});
// 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 pet = self.getPetInForm();
if (self.isEditing()) {
dao.modifyPet(pet,
function(pet) {
$('#pet-' + pet.id + ' td.namePet').text(pet.name);
$('#pet-' + pet.id + ' td.specie').text(pet.specie);
$('#pet-' + pet.id + ' td.idOwner').text(pet.idOwner);
self.resetForm();
},
showErrorMessage,
self.enableForm
);
} else {
dao.addPet(pet,
function(pet) {
daoPeople.getPeople(pet.idOwner,
function(person) {
appendToTable(pet, person);
self.resetForm();
},
showErrorMessage
);
},
showErrorMessage,
self.enableForm
);
}
return false;
});
$('#btnClearPet').click(this.resetForm);
};
this.initPetsPerson = function(id, person) {
$('#' + formContainerId).before('