12 May 2009

Using Dojo DataGrid in Google Gadget

I spent some time last week working with Google Gadgets and Dojo. I had some trouble getting the DataGridrid running in iGoogle at first, so here is a short snippet that shows an example dojo DataGrid running in a Google Gadget.

One mistake I made was calling the initialization methods without using dojo.addOnLoad by registering them just as callbacks for the google onload functionality. That way, the dojo classes were not loaded as expected, which resulted in a lot of weird errors. The solution is calling dojo.addOnLoad from within the callback:

gadgets.util.registerOnLoadHandler(function() {
dojo.addOnLoad(someExampleInitializationFunction);
});

The complete code for the gadget (using dojo 1.3.1) is below:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Dojo Grid Example"
height="400" scrolling="true" />

<Content type="html">
<![CDATA[

<style type="text/css">
@import url("http://ajax.googleapis.com/
ajax/libs/dojo/1.3.1/dojo/resources/dojo.css");
@import url("http://ajax.googleapis.com/
ajax/libs/dojo/1.3.1/dijit/themes/tundra/
tundra.css");
@import url("http://ajax.googleapis.com/
ajax/libs/dojo/1.3.1/dojox/grid/resources/
Grid.css");
@import url("http://ajax.googleapis.com/
ajax/libs/dojo/1.3.1/dojox/grid/resources/
tundraGrid.css");
</style>

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/
libs/dojo/1.3.1/dojo/dojo.xd.js"></script>

<script type="text/javascript">

dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojox.grid.DataGrid");

function init() {

var dataItems = {
identifier: 'id',
label: 'title',
items: [{
'id': 0,
'title': 'This blog',
'url': 'http://lgrammel.blogspot.com/'
},{
'id': 1,
'title': 'My homepage',
'url': 'http://larsgrammel.de/'
}]
};

var store =
new dojo.data.ItemFileReadStore({data: dataItems});

var structure = [{
cells: [{
field: 'title',
name: 'Title',
width: 'auto'
}, {
field: 'url',
name: 'Address',
width: 'auto'
}]
}];

var grid = new dojox.grid.DataGrid({
'store': store,
'structure': structure
}, 'gridNode');

grid.startup();
};

gadgets.util.registerOnLoadHandler(function() {
dojo.addOnLoad(init);
});

</script>

<div id="gridNode"></div>

]]>
</Content>

</Module>

No comments: