HTML5 Guidelines for Web Developers

(coco) #1
7.6 Example: Geonotes 201

The variable i_array is filled with the result of the function getAllItems(), which
reads the localStorage, returns the contents as objects in an array, and sorts the
objects by date:


function getAllItems() {
var i_array = [];
for (var i=0;i<localStorage.length;i++) {
try {
var item = JSON.parse(
localStorage.getItem(localStorage.key(i))
);
i_array.push(item);
} catch (err) {
continue; // skip this entry, no valid JSON data
}
}
i_array.sort(function(a, b) {
return b.ts - a.ts
});
return i_array;
}


The call localStorage.getItem() gets an element from the persistent memory,
converting it to a JavaScript object via the function JSON.parse. The require-
ment is that the object be converted to a string with JSON.stringify during sav-
ing (see the following code listing). To avoid the script being aborted due to any
items in local storage that are not JSON encoded, the instruction is enclosed in
a try/catch block. The objects are added to the end of the array i_array with
i_array.push() and sorted by date in the next step. To tell the JavaScript func-
tion sort which criteria it should sort by, it is expanded with an anonymous
function. The variable ts allows temporal sorting of the objects. It contains the
numbers of milliseconds since 1.1.1970, a value created via the JavaScript func-
tion new Date().getTime(). If the anonymous function returns a negative value,
a is arranged after b; for a positive value, a comes before b.


We still need to answer the question about how new entries are created and
saved. The function saveItem() takes care of this, initializing a local variable d to
which we assign the structure diaryItem:


function saveItem() {
var d = diaryItem;
d.msg = $('note').value;
if (d.msg == '') {
alert("Empty message");
return;
}
d.ts = new Date().getTime();
d.id = "geonotes_"+d.ts;

Free download pdf