PDA

View Full Version : a simplified array reader



aj3423
16 Nov 2010, 12:17 AM
a normal JsonReader reads this kind of data:
[{id:1, name:"name1"}, {id:2, name:"name2"} ... {id:x, name:"namex"}]

see the text marked in red, that's a lot of waste.
an ArrayReader can save the bandwidth, but it needs the backend echo data in sequence, for example:
[[1, "name1"], [2, "name2"],... ,[x, "namex"]]
"name" follows "id", when the backend echo:
[["name1", 1], ["name2", 2],... ,["namex", x]]
the reader won't read correctly, there should be an extra field information:

{
fields: ["name","id"],
data: [["name1", 1], ["name2", 2],... ,["namex", x]]
}

Does Ext already have a reader that can do the above thing? or I should write a MyArrayReader extension?

MyArrayReader = Ext.extend(Ext.data.ArrayReader, { ....

aj3423
21 Nov 2010, 5:55 PM
I tried to write one:


// reader:
FieldArrayReader = Ext.extend(Ext.data.JsonReader, {
readRecords: function(o) {
this.jsonData = o;
var s = this.meta,
sid = s ? Ext.num(s.idIndex, s.id) : null,
recordType = this.recordType,
fields = recordType.prototype.fields,
records = [],
success = true,
v;

var root = this.getRoot(o);

var fs = o['fields'];
for (var i = 0, len = root.length; i < len; i++) {
var n = root[i],
values = {},
id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
for (var j = 0, jlen = fs.length; j < jlen; j++) {
var dataIndex = fs[j];
var f = fields.map[dataIndex];
if(!f) {
continue;
}
var k = f.mapping !== undefined && f.mapping !== null ? f.mapping: j;
v = n[k] !== undefined ? n[k] : f.defaultValue;
v = f.convert(v, n);
values[f.name] = v;
}
var record = new recordType(values, id);
record.json = n;
records[records.length] = record;
}

var totalRecords = records.length;

if (s.totalProperty) {
v = parseInt(this.getTotal(o), 10);
if (!isNaN(v)) {
totalRecords = v;
}
}
if (s.successProperty) {
v = this.getSuccess(o);
if (v === false || v === 'false') {
success = false;
}
}

return {
success: success,
records: records,
totalRecords: totalRecords
};
}
});



//Store:
(function() {

var thisclass;

FieldArrayStore = thisclass = Ext.extend(Ext.data.Store, {
constructor: function(config){
thisclass.superclass.constructor.call(this, Ext.apply(config, {
reader: new Jupiter.arrrdr.FieldArrayReader(config)
}));
}
});
Ext.reg('fieldarraystore', thisclass);

})();

Condor
22 Nov 2010, 1:43 AM
A JsonReader can read array data too if you specify a numeric mapping. It can also read metaData from the JSON data to configure itself.

Example:

{
metaData: {
root: 'data',
fields: [
{name: 'name', mapping: '0'},
{name: 'id', mapping: '1'}
]
},
data: [["name1", 1], ["name2", 2], ..., ["namex", x]]
}

aj3423
22 Nov 2010, 9:03 AM
Thank you Condor, ,....If you post this earlier,,,,