Autonomous Persistence - Ajax Patterns

Autonomous Persistence

From Ajax Patterns

Contents

Code Example

http://ajaxify.com/run/widgets/opensuite/todo/todo.xml

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"));
     renderTasks();

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() {
     renderTasks();
     prefs.set("tasks", JSON.stringify(tasks));
   }

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