Storing Widget Data

Sometimes preferences are not enough for managing widget's state. There are types of widgets that require storing more complex data structures than built-in preferences system can handle.

For this purposes there are special type of methods defined by widget specification that are intended for working with such complex cases.

These methods are:

Method Description
widget.setData(data)Accepts parameter of Array or Object type. Complexity of passed parameter is not restricted
widget.getData()Returns Array or Object that is associated with widgets previous state

Examples of widgets that need to store complex data with it's state are for example Address Book, Bookmarks or Stock Quotes. Data required with these widgets is created and managed by user thus support for storing and retrieving user data is critical.

Note that data stored by noted API methods could be serialized as JSON string, passing an invalid type of object will cause problems. For more information please see JSON specification.

Example of using these methods could be as simple as shown in the code below:

this.onload = function() {
 
   //retrieve previously saved data
   var data = this.getData();
 
   //if data object is not null print data
   if (data) {
      for (var i in data) {
         this.addContent(data.title); 
      }
   } else {
 
      //create data object
      data = {
         title: 'Phone List',
         phones: [
            1235123123,
            0870700709,
            9697690900,
            9769769699
         ]
      };
 
      //store data associated with widget
      this.setData(data);
 
      //save the widget's state
      this.save();
 
   }
 
}

Shown example tries to retrieve previously saved data and if there is no data object associated with widget's current state it creates new data object and saves widget state. This way you can work as complex data structures as required by your widget.