Saving Application State Between Sessions - J Query

Problem

You want to persist data on the client between sessions. Recipe (Using Client-Side Storage) saves the state of the to-do list in between sessions. This recipe illustrates how to enable similar functionality without using the jStore plugin.

Solution

For the HTML part of this solution, please refer to Recipe (Using Client-Side Storage) (as it is identical). The JavaScript is listed here:

The initial setup is somewhat more verbose than the jStore-based solution. Firefox has a nonstandard implementation of the long-term storage portion of the DOM storageAPI. It uses the globalStorage array, as opposed to the localStorage object to persist data between sessions. Each storage object in the globalStorage array is keyed on the domain that the current document is being served from. This code will use localStorage if it is available. Otherwise, it will fall back to globalStorage.
In the next section of code, the unordered list is populated with any existing tasks. In the jStore-based example this was a single line of code. The additional complexity here is because of Firefox’s particular behavior. A string is returned from localStorage. But, an object with two attributes,value and secure, is returned when accessing globalStorage. The value attribute is used if present. Otherwise, a string returned from localStorage is assumed:

The remainder of the code adds new tasks, removes tasks when marked “done,” and clears the task list by attaching events to DOM elements like the previous jStore-based recipe. However, instead of using the jStore function-based interface for manipulating persisted data, values in the appStorage object created earlier can be assigned directly.
This allows the code to remove a task to be simplified.

Discussion

The DOM Storage API consists of two interfaces: sessionStorage and localStorage.
Firefox has included this feature since version 2.0, when the standard was still in development. Since then, the standard has undergone revision. Internet Explorer 8.0 has an implementation of the current API. Forthcoming versions of Safari and Firefox will conform to the current specification as well. That said, Firefox 2.0–3.0 browsers will persist for some time. Coding an application to support globalStorage will additionally serve these legacy browsers.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics