HTML and CSS Reference
In-Depth Information
As discussed above, this function accepts four parameters. When we invoke this from our
task application, the first parameter will always be “task”, while the second parameter will
be an object representing a task. The third and forth parameters are the success and error
callbacks respectively.
Let's step through this implementation line by line.
The first block of code simply checks that init and initObjectStore have been invoked. If
these have not been invoked, the error callback is invoked:
if (!initialized) {
errorCallback('storage_api_not_initialized', 'The storage engine has not been initialized');
} else if (!initializedObjectStores[type]) {
errorCallback('store_not_initialized', 'The object store '+type+' has not been initialized');
The next section of the method checks if the object to be saved has an id or not: if it does
not have an id , a unique id is assigned.
if (! { = $.now();
We next query localStorage for the relevant object store (e.g. “task”). Since initOb-
jectStore has been invoked we can guarantee that there will be an object for the specified
type :
var savedTypeString = localStorage.getItem(type);
Next, we de-serialize the “stringified” version of the object store back into an object:
var storageItem = JSON.parse(savedTypeString);
We then add the object to be saved to the object store, using the id property of the object as
the property name. This will overwrite a value if it is already there, which means the same
code handles creates and updates:
storageItem[] = obj;
Also notice that we are not using the dot notation. Since the id starts with a number, it is
not a valid JavaScript variable name, and therefore the dot notation would not work.
We then serialize storedItem back into a string and add it back into localStorage :
localStorage.setItem(type, JSON.stringify(storageItem));
This will automatically update the item stored against this key.
Search WWH ::

Custom Search