Friday, February 6, 2009

YUI and Google Gears Data Sets

I recently have had some requests to post some examples of how to use YUI with Google Gears. Below is the code for a simple example using the developer's example from Google Gears documentation as a starting guide.

var loader = new YAHOO.util.YUILoader({

require: ['json', 'datatable'],
onSuccess: function(){
var db = google.gears.factory.create('beta.database');'database-test');
db.execute('create table if not exists Test' +
' (Phrase text, Timestamp int)');
db.execute('insert into Test values (?, ?)', ['Monkey!', new Date().getTime()]);
var rs = db.execute('select * from Test order by Timestamp desc');

// Create an object to hold the Results
ResultSet = {rows: []};

var fieldCount = rs.fieldCount();
count = 0;

while (rs.isValidRow()) {
var tmp = {};
for (x = 0; x < fieldCount; x++) {
// Add Each field to tmp object
tmp[rs.fieldName(x)] = rs.field(x);
// Push object onto Results

// YUI DataSource
var dsLocalJSON = new YAHOO.util.LocalDataSource(ResultSet);
dsLocalJSON.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
/* Could also use rs.FieldName here to do dynamic */
dsLocalJSON.responseSchema = {
resultsList: "rows",
fields: ["Phrase", "Timestamp"],
meta: {
totalRecords: count

/* Colum Definitions */
var ColDefs = [{
key: 'Phrase',
label: "The Phrase"
}, {
key: 'Timestamp',
label: 'Epoch',
sortable: true

var DataTable = new YAHOO.widget.DataTable('datatable', ColDefs, dsLocalJSON);

You will of course have to add the proper CSS and JS include files. For this example I used the datatable.css in the sam skin directory, the gears_init.js and YUI Loader js file. You will also need a div with and id='datatable'.

This example will use the loader to get the datatable javascript, as well as the json library. You can use the json library to parse out the record rows you don't need with this.

Hope this helps some people!