Tuesday, 24 August 2010

Using Lawnchair to save config data in a web app

Lawnchair, created by PhoneGap's Brian Leroux, is a simple wrapper to various local storage technologies such as the HTML5 local storage system or even cookies. You can store and retrieve Javascript objects or arrays with just a few lines of code.

We use Lawnchair quite extensively at Calvium. We currently have a few web apps for internal use designed to be run directly from the file system (I'll probably write some more blogs about this subject as it is quite an interesting problem). This is great as it means the web app can read local files using Ajax calls, but due to cross-domain restrictions it cannot send anything to a server. So we can't store anything such as user preferences on the server, so we need to store it locally.
This is where Lawnchair comes in..

The docs don't make a few things very clear, such as how you specify the 'adaptor' to use. This is how you tell the system where data should be stored - cookie, database etc. Here's where my example hopefully may help!



Here's an excerpt of the HTML file. You need to include Lawnchair.js (obviously), and LawnchairAdaptorHelpers.js, and the adaptor you wish to use (in this case WebkitSQLiteAdaptor).

<html>
<head>
   <!--lawnchair-->
    <script type="text/javascript" src="js/libs/Lawnchair.js"></script>
    <script type="text/javascript" src="js/libs/LawnchairAdaptorHelpers.js"></script>
    <script type="text/javascript" src="js/libs/WebkitSQLiteAdaptor.js"></script>
</head>
<body>
   <input type="text" id="myConfigInput"/>
</body>
</html>


(Note: here's a really handy little site for converting HTML example code into a format you can copy into blogger)

Here's the javascript..
 // create the lawnchair object, telling it to create a table called myapp, using the 'WebkitSQLListAdaptor'.
var _lawnchair = new Lawnchair({table: "myapp", adaptor: "webkit"});

// create the javascript object with my default data in it.
var _config = {"userSetting":"", "key": "config"};
// key is the string used to get the data out in the 'get' call below.

// Load the config
_lawnchair.get("config", function(r) {

// If there isn't an item in the database with the 'config' key set, you'll get null. Make sure we don't overwrite the default!
if (r !== null) {
_log("LoadFileDialog: config loaded.");

// TODO: might be better to merge..
_config = r;

// Update interface with the values we've loaded.
}
});

// Note that the get function is asynchronous, so the get may not have completed by this point.

1 comment: