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