~mortenoh/+junk/dhis2-detailed-import-export

« back to all changes in this revision

Viewing changes to gis/dhis-gis-geostat/mfbase/ext/source/data/JsonReader.js

  • Committer: larshelge at gmail
  • Date: 2009-03-03 16:46:36 UTC
  • Revision ID: larshelge@gmail.com-20090303164636-2sjlrquo7ib1gf7r
Initial check-in

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Ext JS Library 2.2
 
3
 * Copyright(c) 2006-2008, Ext JS, LLC.
 
4
 * licensing@extjs.com
 
5
 * 
 
6
 * http://extjs.com/license
 
7
 */
 
8
 
 
9
/**
 
10
 * @class Ext.data.JsonReader
 
11
 * @extends Ext.data.DataReader
 
12
 * Data reader class to create an Array of {@link Ext.data.Record} objects from a JSON response
 
13
 * based on mappings in a provided {@link Ext.data.Record} constructor.<br>
 
14
 * <p>
 
15
 * Example code:
 
16
 * <pre><code>
 
17
var Employee = Ext.data.Record.create([
 
18
    {name: 'firstname'},                  // Map the Record's "firstname" field to the row object's key of the same name
 
19
    {name: 'job', mapping: 'occupation'}  // Map the "job" field to the row object's "occupation" key
 
20
]);
 
21
var myReader = new Ext.data.JsonReader({
 
22
    totalProperty: "results",             // The property which contains the total dataset size (optional)
 
23
    root: "rows",                         // The property which contains an Array of row objects
 
24
    id: "id"                              // The property within each row object that provides an ID for the record (optional)
 
25
}, Employee);
 
26
</code></pre>
 
27
 * <p>
 
28
 * This would consume a JSON object of the form:
 
29
 * <pre><code>
 
30
{
 
31
    'results': 2,
 
32
    'rows': [
 
33
        { 'id': 1, 'firstname': 'Bill', occupation: 'Gardener' },         // a row object
 
34
        { 'id': 2, 'firstname': 'Ben' , occupation: 'Horticulturalist' }  // another row object
 
35
    ]
 
36
}
 
37
</code></pre>
 
38
 * <p>It is possible to change a JsonReader's metadata at any time by including a
 
39
 * <b><tt>metaData</tt></b> property in the data object. If this is detected in the
 
40
 * object, a {@link Ext.data.Store Store} object using this Reader will fire its
 
41
 * {@link Ext.data.Store#metachange metachange} event.</p>
 
42
 * <p>The <b><tt>metaData</tt></b> property may contain any of the configuration
 
43
 * options for this class. Additionally, it may contain a <b><tt>fields</tt></b>
 
44
 * property which the JsonReader will use as an argument to {@link Ext.data.Record#create}
 
45
 * to configure the layout of the Records which it will produce.<p>
 
46
 * Using the <b><tt>metaData</tt></b> property, and the Store's {@link Ext.data.Store#metachange metachange} event,
 
47
 * it is possible to have a Store-driven control initialize itself. The metachange
 
48
 * event handler may interrogate the <b><tt>metaData</tt></b> property (which
 
49
 * may contain any user-defined properties needed) and the <b><tt>metaData.fields</tt></b>
 
50
 * property to perform any configuration required.</p>
 
51
 * <p>To use this facility to send the same data as the above example without
 
52
 * having to code the creation of the Record constructor, you would create the
 
53
 * JsonReader like this:</p><pre><code>
 
54
var myReader = new Ext.data.JsonReader();
 
55
</code></pre>
 
56
 * <p>The first data packet from the server would configure the reader by
 
57
 * containing a metaData property as well as the data:</p><pre><code>
 
58
{
 
59
  'metaData': {
 
60
    totalProperty: 'results',
 
61
    root: 'rows',
 
62
    id: 'id',
 
63
    fields: [
 
64
      {name: 'name'},
 
65
      {name: 'occupation'} ]
 
66
   },
 
67
  'results': 2, 'rows': [
 
68
    { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
 
69
    { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
 
70
}
 
71
</code></pre>
 
72
 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
 
73
 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
 
74
 * paged from the remote server.
 
75
 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
 
76
 * @cfg {String} root name of the property which contains the Array of row objects.
 
77
 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
 
78
 * @constructor
 
79
 * Create a new JsonReader
 
80
 * @param {Object} meta Metadata configuration options.
 
81
 * @param {Object} recordType Either an Array of field definition objects as passed to
 
82
 * {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record} constructor created using {@link Ext.data.Record#create}.
 
83
 */
 
84
Ext.data.JsonReader = function(meta, recordType){
 
85
    meta = meta || {};
 
86
    Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
 
87
};
 
88
Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
 
89
    /**
 
90
     * This JsonReader's metadata as passed to the constructor, or as passed in
 
91
     * the last data packet's <b><tt>metaData</tt></b> property.
 
92
     * @type Mixed
 
93
     * @property meta
 
94
     */
 
95
    /**
 
96
     * This method is only used by a DataProxy which has retrieved data from a remote server.
 
97
     * @param {Object} response The XHR object which contains the JSON data in its responseText.
 
98
     * @return {Object} data A data block which is used by an Ext.data.Store object as
 
99
     * a cache of Ext.data.Records.
 
100
     */
 
101
    read : function(response){
 
102
        var json = response.responseText;
 
103
        var o = eval("("+json+")");
 
104
        if(!o) {
 
105
            throw {message: "JsonReader.read: Json object not found"};
 
106
        }
 
107
        return this.readRecords(o);
 
108
    },
 
109
 
 
110
    // private function a store will implement
 
111
    onMetaChange : function(meta, recordType, o){
 
112
 
 
113
    },
 
114
 
 
115
    /**
 
116
         * @ignore
 
117
         */
 
118
    simpleAccess: function(obj, subsc) {
 
119
        return obj[subsc];
 
120
    },
 
121
 
 
122
        /**
 
123
         * @ignore
 
124
         */
 
125
    getJsonAccessor: function(){
 
126
        var re = /[\[\.]/;
 
127
        return function(expr) {
 
128
            try {
 
129
                return(re.test(expr))
 
130
                    ? new Function("obj", "return obj." + expr)
 
131
                    : function(obj){
 
132
                        return obj[expr];
 
133
                    };
 
134
            } catch(e){}
 
135
            return Ext.emptyFn;
 
136
        };
 
137
    }(),
 
138
 
 
139
    /**
 
140
     * Create a data block containing Ext.data.Records from a JSON object.
 
141
     * @param {Object} o An object which contains an Array of row objects in the property specified
 
142
     * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
 
143
     * which contains the total size of the dataset.
 
144
     * @return {Object} data A data block which is used by an Ext.data.Store object as
 
145
     * a cache of Ext.data.Records.
 
146
     */
 
147
    readRecords : function(o){
 
148
        /**
 
149
         * After any data loads, the raw JSON data is available for further custom processing.  If no data is
 
150
         * loaded or there is a load exception this property will be undefined.
 
151
         * @type Object
 
152
         */
 
153
        this.jsonData = o;
 
154
        if(o.metaData){
 
155
            delete this.ef;
 
156
            this.meta = o.metaData;
 
157
            this.recordType = Ext.data.Record.create(o.metaData.fields);
 
158
            this.onMetaChange(this.meta, this.recordType, o);
 
159
        }
 
160
        var s = this.meta, Record = this.recordType,
 
161
            f = Record.prototype.fields, fi = f.items, fl = f.length;
 
162
 
 
163
//      Generate extraction functions for the totalProperty, the root, the id, and for each field
 
164
        if (!this.ef) {
 
165
            if(s.totalProperty) {
 
166
                    this.getTotal = this.getJsonAccessor(s.totalProperty);
 
167
                }
 
168
                if(s.successProperty) {
 
169
                    this.getSuccess = this.getJsonAccessor(s.successProperty);
 
170
                }
 
171
                this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
 
172
                if (s.id) {
 
173
                        var g = this.getJsonAccessor(s.id);
 
174
                        this.getId = function(rec) {
 
175
                                var r = g(rec);
 
176
                                return (r === undefined || r === "") ? null : r;
 
177
                        };
 
178
                } else {
 
179
                        this.getId = function(){return null;};
 
180
                }
 
181
            this.ef = [];
 
182
            for(var i = 0; i < fl; i++){
 
183
                f = fi[i];
 
184
                var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
 
185
                this.ef[i] = this.getJsonAccessor(map);
 
186
            }
 
187
        }
 
188
 
 
189
        var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
 
190
        if(s.totalProperty){
 
191
            var v = parseInt(this.getTotal(o), 10);
 
192
            if(!isNaN(v)){
 
193
                totalRecords = v;
 
194
            }
 
195
        }
 
196
        if(s.successProperty){
 
197
            var v = this.getSuccess(o);
 
198
            if(v === false || v === 'false'){
 
199
                success = false;
 
200
            }
 
201
        }
 
202
        var records = [];
 
203
            for(var i = 0; i < c; i++){
 
204
                    var n = root[i];
 
205
                var values = {};
 
206
                var id = this.getId(n);
 
207
                for(var j = 0; j < fl; j++){
 
208
                    f = fi[j];
 
209
                var v = this.ef[j](n);
 
210
                values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, n);
 
211
                }
 
212
                var record = new Record(values, id);
 
213
                record.json = n;
 
214
                records[i] = record;
 
215
            }
 
216
            return {
 
217
                success : success,
 
218
                records : records,
 
219
                totalRecords : totalRecords
 
220
            };
 
221
    }
 
222
});
 
 
b'\\ No newline at end of file'