Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / docs / source / JsonReader.html
1 <html>
2 <head>
3   <title>The source code</title>
4     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
5     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
6 </head>
7 <body  onload="prettyPrint();">
8     <pre class="prettyprint lang-js">/*!
9  * Ext JS Library 3.0.3
10  * Copyright(c) 2006-2009 Ext JS, LLC
11  * licensing@extjs.com
12  * http://www.extjs.com/license
13  */
14 <div id="cls-Ext.data.JsonReader"></div>/**
15  * @class Ext.data.JsonReader
16  * @extends Ext.data.DataReader
17  * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
18  * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
19  * constructor.</p>
20  * <p>Example code:</p>
21  * <pre><code>
22 var myReader = new Ext.data.JsonReader({
23     // metadata configuration options:
24     {@link #idProperty}: 'id'
25     {@link #root}: 'rows',
26     {@link #totalProperty}: 'results',
27     {@link Ext.data.DataReader#messageProperty}: "msg"  // The element within the response that provides a user-feedback message (optional)
28
29     // the fields config option will internally create an {@link Ext.data.Record}
30     // constructor that provides mapping for reading the record data objects
31     {@link Ext.data.DataReader#fields fields}: [
32         // map Record&#39;s 'firstname' field to data object&#39;s key of same name
33         {name: 'name'},
34         // map Record&#39;s 'job' field to data object&#39;s 'occupation' key
35         {name: 'job', mapping: 'occupation'}
36     ]
37 });
38 </code></pre>
39  * <p>This would consume a JSON data object of the form:</p><pre><code>
40 {
41     results: 2000, // Reader&#39;s configured {@link #totalProperty}
42     rows: [        // Reader&#39;s configured {@link #root}
43         // record data objects:
44         { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
45         { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
46         ...
47     ]
48 }
49 </code></pre>
50  * <p><b><u>Automatic configuration using metaData</u></b></p>
51  * <p>It is possible to change a JsonReader's metadata at any time by including
52  * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
53  * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
54  * object using this Reader will reconfigure itself to use the newly provided
55  * field definition and fire its {@link Ext.data.Store#metachange metachange}
56  * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
57  * property to perform any configuration required.</p>
58  * <p>Note that reconfiguring a Store potentially invalidates objects which may
59  * refer to Fields or Records which no longer exist.</p>
60  * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
61 var myReader = new Ext.data.JsonReader();
62 </code></pre>
63  * <p>The first data packet from the server would configure the reader by
64  * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
65  * example, the JSON data object might take the form:</p><pre><code>
66 {
67     metaData: {
68         "{@link #idProperty}": "id",
69         "{@link #root}": "rows",
70         "{@link #totalProperty}": "results"
71         "{@link #successProperty}": "success",
72         "{@link Ext.data.DataReader#fields fields}": [
73             {"name": "name"},
74             {"name": "job", "mapping": "occupation"}
75         ],
76         // used by store to set its sortInfo
77         "sortInfo":{
78            "field": "name",
79            "direction": "ASC"
80         },
81         // {@link Ext.PagingToolbar paging data} (if applicable)
82         "start": 0,
83         "limit": 2,
84         // custom property
85         "foo": "bar"
86     },
87     // Reader&#39;s configured {@link #successProperty}
88     "success": true,
89     // Reader&#39;s configured {@link #totalProperty}
90     "results": 2000,
91     // Reader&#39;s configured {@link #root}
92     // (this data simulates 2 results {@link Ext.PagingToolbar per page})
93     "rows": [ // <b>*Note:</b> this must be an Array
94         { "id": 1, "name": "Bill", "occupation": "Gardener" },
95         { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
96     ]
97 }
98  * </code></pre>
99  * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
100  * <div class="mdetail-params"><ul>
101  * <li>any of the configuration options for this class</li>
102  * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
103  * the JsonReader will use as an argument to the
104  * {@link Ext.data.Record#create data Record create method} in order to
105  * configure the layout of the Records it will produce.</li>
106  * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
107  * which the JsonReader will use to set the {@link Ext.data.Store}'s
108  * {@link Ext.data.Store#sortInfo sortInfo} property</li>
109  * <li>any custom properties needed</li>
110  * </ul></div>
111  *
112  * @constructor
113  * Create a new JsonReader
114  * @param {Object} meta Metadata configuration options.
115  * @param {Array/Object} recordType
116  * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
117  * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
118  * constructor created from {@link Ext.data.Record#create}.</p>
119  */
120 Ext.data.JsonReader = function(meta, recordType){
121     meta = meta || {};
122     <div id="cfg-Ext.data.JsonReader-idProperty"></div>/**
123      * @cfg {String} idProperty [id] Name of the property within a row object
124      * that contains a record identifier value.  Defaults to <tt>id</tt>
125      */
126     <div id="cfg-Ext.data.JsonReader-successProperty"></div>/**
127      * @cfg {String} successProperty [success] Name of the property from which to
128      * retrieve the success attribute. Defaults to <tt>success</tt>.  See
129      * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
130      * for additional information.
131      */
132     <div id="cfg-Ext.data.JsonReader-totalProperty"></div>/**
133      * @cfg {String} totalProperty [total] Name of the property from which to
134      * retrieve the total number of records in the dataset. This is only needed
135      * if the whole dataset is not passed in one go, but is being paged from
136      * the remote server.  Defaults to <tt>total</tt>.
137      */
138     <div id="cfg-Ext.data.JsonReader-root"></div>/**
139      * @cfg {String} root [undefined] <b>Required</b>.  The name of the property
140      * which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
141      * An exception will be thrown if the root property is undefined. The data
142      * packet value for this property should be an empty array to clear the data
143      * or show no data.
144      */
145     Ext.applyIf(meta, {
146         idProperty: 'id',
147         successProperty: 'success',
148         totalProperty: 'total'
149     });
150
151     Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
152 };
153 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
154     <div id="prop-Ext.data.JsonReader-meta"></div>/**
155      * This JsonReader's metadata as passed to the constructor, or as passed in
156      * the last data packet's <b><tt>metaData</tt></b> property.
157      * @type Mixed
158      * @property meta
159      */
160     <div id="method-Ext.data.JsonReader-read"></div>/**
161      * This method is only used by a DataProxy which has retrieved data from a remote server.
162      * @param {Object} response The XHR object which contains the JSON data in its responseText.
163      * @return {Object} data A data block which is used by an Ext.data.Store object as
164      * a cache of Ext.data.Records.
165      */
166     read : function(response){
167         var json = response.responseText;
168         var o = Ext.decode(json);
169         if(!o) {
170             throw {message: 'JsonReader.read: Json object not found'};
171         }
172         return this.readRecords(o);
173     },
174
175     <div id="method-Ext.data.JsonReader-readResponse"></div>/**
176      * Decode a json response from server.
177      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
178      * @param {Object} response
179      * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
180      * there's ugly duplication going on due to maintaining backwards compat. with 2.0.  It's time to do this.
181      */
182     readResponse : function(action, response) {
183         var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
184         if(!o) {
185             throw new Ext.data.JsonReader.Error('response');
186         }
187
188         var root = this.getRoot(o);
189         if (action === Ext.data.Api.actions.create) {
190             var def = Ext.isDefined(root);
191             if (def && Ext.isEmpty(root)) {
192                 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
193             }
194             else if (!def) {
195                 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
196             }
197         }
198
199         // instantiate response object
200         var res = new Ext.data.Response({
201             action: action,
202             success: this.getSuccess(o),
203             data: this.extractData(root),
204             message: this.getMessage(o),
205             raw: o
206         });
207
208         // blow up if no successProperty
209         if (Ext.isEmpty(res.success)) {
210             throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
211         }
212         return res;
213     },
214
215     <div id="method-Ext.data.JsonReader-readRecords"></div>/**
216      * Create a data block containing Ext.data.Records from a JSON object.
217      * @param {Object} o An object which contains an Array of row objects in the property specified
218      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
219      * which contains the total size of the dataset.
220      * @return {Object} data A data block which is used by an Ext.data.Store object as
221      * a cache of Ext.data.Records.
222      */
223     readRecords : function(o){
224         <div id="prop-Ext.data.JsonReader-jsonData"></div>/**
225          * After any data loads, the raw JSON data is available for further custom processing.  If no data is
226          * loaded or there is a load exception this property will be undefined.
227          * @type Object
228          */
229         this.jsonData = o;
230         if(o.metaData){
231             this.onMetaChange(o.metaData);
232         }
233         var s = this.meta, Record = this.recordType,
234             f = Record.prototype.fields, fi = f.items, fl = f.length, v;
235
236         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
237         if(s.totalProperty){
238             v = parseInt(this.getTotal(o), 10);
239             if(!isNaN(v)){
240                 totalRecords = v;
241             }
242         }
243         if(s.successProperty){
244             v = this.getSuccess(o);
245             if(v === false || v === 'false'){
246                 success = false;
247             }
248         }
249
250         // TODO return Ext.data.Response instance instead.  @see #readResponse
251         return {
252             success : success,
253             records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
254             totalRecords : totalRecords
255         };
256     },
257
258     // private
259     buildExtractors : function() {
260         if(this.ef){
261             return;
262         }
263         var s = this.meta, Record = this.recordType,
264             f = Record.prototype.fields, fi = f.items, fl = f.length;
265
266         if(s.totalProperty) {
267             this.getTotal = this.createAccessor(s.totalProperty);
268         }
269         if(s.successProperty) {
270             this.getSuccess = this.createAccessor(s.successProperty);
271         }
272         if (s.messageProperty) {
273             this.getMessage = this.createAccessor(s.messageProperty);
274         }
275         this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
276         if (s.id || s.idProperty) {
277             var g = this.createAccessor(s.id || s.idProperty);
278             this.getId = function(rec) {
279                 var r = g(rec);
280                 return (r === undefined || r === '') ? null : r;
281             };
282         } else {
283             this.getId = function(){return null;};
284         }
285         var ef = [];
286         for(var i = 0; i < fl; i++){
287             f = fi[i];
288             var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
289             ef.push(this.createAccessor(map));
290         }
291         this.ef = ef;
292     },
293
294     /**
295      * @ignore
296      * TODO This isn't used anywhere??  Don't we want to use this where possible instead of complex #createAccessor?
297      */
298     simpleAccess : function(obj, subsc) {
299         return obj[subsc];
300     },
301
302     /**
303      * @ignore
304      */
305     createAccessor : function(){
306         var re = /[\[\.]/;
307         return function(expr) {
308             try {
309                 return(re.test(expr)) ?
310                 new Function('obj', 'return obj.' + expr) :
311                 function(obj){
312                     return obj[expr];
313                 };
314             } catch(e){}
315             return Ext.emptyFn;
316         };
317     }(),
318
319     /**
320      * returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row
321      * @param {Object[]/Object} data-root from server response
322      * @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record
323      * @private
324      */
325     extractData : function(root, returnRecords) {
326         var rs = undefined;
327         if (this.isData(root)) {
328             root = [root];
329         }
330         if (Ext.isArray(root)) {
331             var f       = this.recordType.prototype.fields,
332                 fi      = f.items,
333                 fl      = f.length,
334                 rs      = [];
335             if (returnRecords === true) {
336                 var Record = this.recordType;
337                 for (var i = 0; i < root.length; i++) {
338                     var n = root[i];
339                     var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
340                     record.json = n;
341                     rs.push(record);
342                 }
343             }
344             else {
345                 for (var i = 0; i < root.length; i++) {
346                     rs.push(this.extractValues(root[i], fi, fl));
347                 }
348             }
349         }
350         return rs;
351     },
352
353     /**
354      * type-casts a single row of raw-data from server
355      * @param {Object} data
356      * @param {Array} items
357      * @param {Integer} len
358      * @private
359      */
360     extractValues : function(data, items, len) {
361         var f, values = {};
362         for(var j = 0; j < len; j++){
363             f = items[j];
364             var v = this.ef[j](data);
365             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
366         }
367         return values;
368     }
369 });
370
371 <div id="cls-Ext.data.JsonReader.Error"></div>/**
372  * @class Ext.data.JsonReader.Error
373  * Error class for JsonReader
374  */
375 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
376     constructor : function(message, arg) {
377         this.arg = arg;
378         Ext.Error.call(this, message);
379     },
380     name : 'Ext.data.JsonReader'
381 });
382 Ext.apply(Ext.data.JsonReader.Error.prototype, {
383     lang: {
384         'response': 'An error occurred while json-decoding your server response',
385         'successProperty-response': 'Could not locate your "successProperty" in your server response.  Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response.  See the JsonReader docs.',
386         'root-undefined-config': 'Your JsonReader was configured without a "root" property.  Please review your JsonReader config and make sure to define the root property.  See the JsonReader docs.',
387         'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty"  Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id").  See the JsonReader docs.',
388         'root-empty': 'Data was expected to be returned by the server in the "root" property of the response.  Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response.  See JsonReader docs.'
389     }
390 });
391 </pre>
392 </body>
393 </html>