Storing drawings in websql

The DB module skeleton.

 1// DB Module
 2;(function(){
 3  var app = this.app || (this.app={});
 4
 5  var DB = app.DB = (function(){
 6    function DB() {
 7      // init the database
 8    }
 9    DB.prototype.insert = function(drawing)
10    {
11      // insert the entry into database
12    };
13    DB.prototype.query = function(callback)
14    {
15      // query the data from database
16    };
17    return DB;
18  })();
19}).call(this);

Opening the database.

1function DB() {
2  // init the database
3  this.db = openDatabase("drawings", "1.0", "Drawing DB", 1024*1024*10);
4  // create the table
5  this.db.transaction(function(tx){
6    tx.executeSql('CREATE TABLE IF NOT EXISTS entries (drawing text)');
7  });
8}

Executing INSERT SQL.

1DB.prototype.insert = function(drawing)
2{
3  // insert the entry into database
4  this.db.transaction(function(tx){
5    tx.executeSql('INSERT INTO entries(drawing) VALUES(?)', [drawing]);
6  });
7};

Fetching data from database with SELECT.

 1DB.prototype.query = function(callback)
 2{
 3  // query the data from database
 4  this.db.transaction(function(tx){
 5    tx.executeSql('SELECT * FROM entries', [], function(tx, results){
 6      // convert the results SQL collection into normal Array
 7      var array = [];
 8      for (var i=0, len = results.rows.length; i < len; i++) {
 9        var entry = results.rows.item(i);
10        array.push(entry.drawing);
11      };
12      // finally send the result to the callback.
13      if (callback) callback(array);
14    });
15  });
16};

That’s all for the Database module. Now we are back to our app logic.

First, we load the stored drawings when the page is loaded and ready.

1app.db = new app.DB();
2
3app.loadDrawingsFromDB = function(callback) {
4  app.db.query(function(results){
5    app.drawings = results;
6    callback();
7  });
8};

Now whenever we save the drawings, we insert it to our database as well.

1$('#save-drawing').click(function(){
2  var data = app.drawingPad.data();
3  // existing code here
4
5  // save to DB
6  app.db.insert(data);
7});

What’s next? We’re going to take a look at “Phonegap device ready event”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content