Practice exercises CHAPTER 15 575
displayCurrentRecord();
var results = retrieveFromStorage();
bindToGrid(results);
};
- Add the public save method. In this method, create a contact variable and assign the
contact property of currentRecord. Retrieve each of the field values from the form and
assign them to the contact object as follows.
ns.save = function () {
var contact = currentRecord.contact;
contact.firstName = $('#firstName').val();
contact.lastName = $('#lastName').val();
contact.email = $('#email').val();
contact.phoneNumber = $('#phoneNumber').val();
}; - Add logic to the end of the save method that either adds the contact to the array if it’s
a new contact or updates the contact if it already exists. Convert the object to a JSON
string and store it in localStorage. Update the page by calling the display method.
The completed save method is as follows.
ns.save = function () {
var contact = currentRecord.contact;
contact.firstName = $('#firstName').val();
contact.lastName = $('#lastName').val();
contact.email = $('#email').val();
contact.phoneNumber = $('#phoneNumber').val();
var results = retrieveFromStorage();
if (currentRecord.key != null) {
results[currentRecord.key] = contact;
}
else {
results.push(contact);
}
localStorage.setItem('contacts', JSON.stringify(results));
ns.display();
};
- Update the initialize method to bind the save button and invoke the display() method.
ns.initialize = function () {
$('#btnSave').on('click', ns.save);
ns.display();
};
Your JavaScript file should look like the following.
/// <reference path="jquery-1.8.3.js" />
$(document).ready(function () {
contactsNamespace.initialize();