Getting into Gears: Offline Web App Tutorial – Part 2

GearsIn the first part of this tutorial I took a look at some of the background to Gears; the code example showed how to initialise Gears, and create a database (with a table definition). Apologies for the delay in getting the second part out of the drafts section of the blog.

In this section, I’ll show how to use the Gears WorkerPool to carry out operations without affecting the user interface. Also included is a simple example of using the Gears HTTPRequest object to retrieve data from the remote database.

Read the first part of the tutorial.

Using the WorkerPool

The Gears Workerpool allows JavaScript to run in the background without affecting the performance of browser window. This means that the user’s browser won’t slow down or lock up while there is processing going on behind the scenes. This gives the  opportunity to create more intensive scripts, and to have your web application process information while the user carries on with their other work.


// create a workerpool
var workerPool = google.gears.factory.create('beta.workerpool');
// handle messages from the worker
workerPool.onmessage = function(a, b, message) {
console.log('Received message from worker ' + message.sender + ': \n' + message.body);
};
// create a child worker from a URL
var childWorkerId = workerPool.createWorkerFromUrl('/scripts/gears/gears_db_load.js');
// send the child a message... (messageBody, Unique Worker ID)
workerPool.sendMessage("loadAllTreat", childWorkerId);

When the function is called it creates a Workerpool object (more details from the Gears Workerpool API). This is used to create individual Workers that can be set to do different jobs. The Workers do not have access to the Window object, which means that they must interact by sending messages to each other.  The “workerPool.onmessage” callback above is an example of how Workers accept messages from each other (in this case, the details of the message (the Worker that sent it, and the message body) are being written to the Firebug console window.

The line:

var childWorkerId = workerPool.createWorkerFromUrl('/scripts/gears/gears_db_load.js');

is creating a Worker from an external script – gears_db_load.js (more on that in a moment).  The createWorkerFromUrl method returns a unique id value for the Worker – it is using this that the destination of messages sent between Workers is known.

The final line above sends a message to the Worker; in this case, telling it what action to take. The second parameter is the id value of the Worker, which allows the message to be routed to the correct place.

My First Worker


// gears_db_load.js
/*
Workerpool JS to load remote data to local db after Setup
*/
(function(){
var wp = google.gears.workerPool;
var sender; // Parent Worker ID
// handle incoming messages:
wp.onmessage = function(a, b, message) {
try{
var msg = message.body; // what was the message
sender = message.sender; // Where did the message come from
var resp; // response to be returned to the Parent Worker
switch (msg)
{
case 'loadAllTreat':
getAllTreatments(); /* call a function to do something...*/
break;
default:
resp = 'Oops...no message sent!!';
wp.sendMessage(resp, sender);
break;
}
} // try
catch(ex)
{ // send back an error message if needed
wp.sendMessage('Error in worker: '+ err.message, sender);
}
} // onmessage


// handle any errors that come up...
wp.onerror = function( err ){
wp.sendMessage('Error in worker: '+ err.message, sender);
return true;
}

This is creating a new Worker, and uses the onmessage callback to check what message has been passed to it by the sender. A switch statement is used to decide what action is needed, based on the message passed in. In this example, if the message is “loadAllTreat" the function getAllTreatments() is called, otherwise, a message is passed back to the sender.

Also included is an onerror callback that is used to return an error message to the sender, should an error occur.

Gears HTTPRequest

The getAllTreatments() function uses the Gears HTTPRequest to get data from the server using AJAX. The code below demonstrates carrying out the request, and parsing the JSON response from the server. [Note: it stops short of doing anything with the data returned – this will depend on the application in question]

function getAllTreatments(){
var request = google.gears.factory.create('beta.httprequest');
// get Treatment & Treatment Category Data
request.open('GET', '/path/to/my/data/');
request.onreadystatechange = function() {
if (request.readyState == 4) {
try{
response = request.responseText;
var jsResp = json_parse(response); // using http://www.JSON.org/json_parse.js
//...
// do something with the json response, for example, insert it into local database..
//...
}// try
catch(ex){
wp.sendMessage("Worker Error: line - "+ ex.lineNumber + " Ex: "+ ex.message, sender);
} // catch
} // readystate
}; // onstatechange
request.send();
} // getAllTreatments()

The “var request” holds a Gears httpRequest object. It needs a place to request the data from, which is added using “request.open”, and supplying request type (“GET”) the path to the data (‘/path/to/my/data’). When the request completes, the if statement within the onreadystatechange callback is triggered. This parses the response (in this example, the server is supplying a JSON response) using json_parse (available from: http://www.JSON.org/json_parse.js.

The example above stops short of doing something with the response after it has been parsed. One example of what could be done with the data, is to insert it into the local database.

Other Alternatives

There are a number of options available for implementing offline web apps. Some examples include:

Related