Tuesday, November 18, 2008

Ext JS - How to hack the JsonReader

I have a new job ( hooooray?! ) and I suggested Ext JS framework as web UI to focus more about Ajax, XML + XSLT data interactions rather than problems with CSS, events delegations, etc ... and I guess I am doing well, so well, that here I am with a simple tiny trick to hack an Ext.data.JsonReader instance, specially the root and the totalProperty params:

// directly from Ext JS 2.2 API site
// http://extjs.com/deploy/dev/docs/

new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
})

Especially for the paginator toolbar, the JsonReader is a must to surf a big amount of data without stressing too much both server and client sides.

One nice feature, or one clever way to make the root node customizable, is the usage of evaluated code via a new Function call.

If the root property ontains a dot, that property is retrieved via nested objec properties.


...
root:"items[0].myList",
...

Thanks to this feature, it is possible to pre parse and pre generate the list that will be assigned as root Array, the one used inside the Grid, DataView, or whatever.Component is managing your interactions.

The trick to pass the returned object to an arbitrary function is this:

...
root:"toString.length||callback(obj)",
...

The callback suppose to be a valid function with a global scope that will return a filtered list of objects compatible with the column model or the data manager we chose.

The trick is based on their regexp that checks simply a dot or a square bracket "[" in the passed string.

That's it, let me discover better tricky stuff in the source and I'll post them :D