Autonomous Persistence - Ajax Patterns

Autonomous Persistence

From Ajax Patterns


Code Example

A hidden preference is declared. tasks is a serialised form of the tasks data structure, and we use JSON as the string format. tasks is initially "[]", the JSON value for an empty list.

 <UserPref name="tasks" default_value= "[]" datatype="hidden" />

On gadget startup, we "thaw out" the list of tasks and render it.

     tasks = JSON.parse(prefs.getString("tasks"));

Each time the list of tasks change, we re-display it and set our tasks preference to a JSONified representation of tasks. Every function that changes tasks, such as addTask() and deleteTask(), calls this function after the change is made. It's a simplified version of the Publish-Subscribe - or Observer - pattern.

   function onTasksChanged() {
     prefs.set("tasks", JSON.stringify(tasks));

Using hidden preferences in this way, we have delegated persistence to our friend, the container.