Description
Extra 16-1 Develop a Contact List app that uses JSON
In this exercise, you’ll develop a Contact List application that uses the JSON object to convert objects to strings and back again for storage in local storage. The application looks like this:
And this is the JSON string that’s stored in local s..n@bletchleypark.uk”}]
1. Open the HTML and JavaScript files
2. Review the code in the contact_list.js file. Note that it uses a storage object and Contact objects to add and display contacts.
3. In the library_storage.js file, add code to the getContacts method that converts a string to a JavaScript object and returns it, or returns an empty array if the string is null.
4. Still in the library_storage.js file, add code to the setContacts method that converts a JavaScript object to a string.
5. In the library_contact.js file, review the code for the Contact constructor function and its methods. Then, add code to the toJSON method that shortens the property names (you can refer to the JSON string above to see what the short names should be).
6. Still in the library_contact.js file, add code to the loadJsonObject method that uses the object with short names to populate the Contact object’s properties.
7. Run and test the application. Notice that it allows you to store a phone number with dashes, slashes, plus signs, etc., but it displays the phone numbers exactly as you enter them.
Files:
contact_list.css
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
input[type=”button”] {
width: 10.5em;
}
.clear {
clear: both;
}
#contacts {
width: 50%;
margin: 0 3em 0 0;
float: right;
}
contact_list.js
“use strict”;
var $ = function (id) { return document.getElementById(id); };
var contacts = [];
var displayContacts = function () {
// clear previous
contacts.length = 0;
$(“contacts”).innerHTML = “”;
// get contacts from storage and initialize a variable to hold html string
var array = storage.getContacts();
var html = “”;
// loop array from storage, create new Contact objects, store
// them in contacts array and use the displayContact method for display
for (var i = 0; i < array.length; i++) { var contact = new Contact(); contact.loadJsonObject(array[i]); html = html.concat("