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>
7 <body onload="prettyPrint();">
8 <pre class="prettyprint lang-js">/*!
10 * Copyright(c) 2006-2009 Ext JS, LLC
12 * http://www.extjs.com/license
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}
20 * <p>Example code:</p>
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)
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's 'firstname' field to data object's key of same name
34 // map Record's 'job' field to data object's 'occupation' key
35 {name: 'job', mapping: 'occupation'}
39 * <p>This would consume a JSON data object of the form:</p><pre><code>
41 results: 2000, // Reader's configured {@link #totalProperty}
42 rows: [ // Reader'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' },
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();
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>
68 "{@link #idProperty}": "id",
69 "{@link #root}": "rows",
70 "{@link #totalProperty}": "results"
71 "{@link #successProperty}": "success",
72 "{@link Ext.data.DataReader#fields fields}": [
74 {"name": "job", "mapping": "occupation"}
76 // used by store to set its sortInfo
81 // {@link Ext.PagingToolbar paging data} (if applicable)
87 // Reader's configured {@link #successProperty}
89 // Reader's configured {@link #totalProperty}
91 // Reader'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" }
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>
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>
120 Ext.data.JsonReader = function(meta, recordType){
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>
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.
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>.
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
147 successProperty: 'success',
148 totalProperty: 'total'
151 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
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.
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.
166 read : function(response){
167 var json = response.responseText;
168 var o = Ext.decode(json);
170 throw {message: 'JsonReader.read: Json object not found'};
172 return this.readRecords(o);
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.
182 readResponse : function(action, response) {
183 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
185 throw new Ext.data.JsonReader.Error('response');
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);
195 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
199 // instantiate response object
200 var res = new Ext.data.Response({
202 success: this.getSuccess(o),
203 data: this.extractData(root),
204 message: this.getMessage(o),
208 // blow up if no successProperty
209 if (Ext.isEmpty(res.success)) {
210 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
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.
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.
231 this.onMetaChange(o.metaData);
233 var s = this.meta, Record = this.recordType,
234 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
236 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
238 v = parseInt(this.getTotal(o), 10);
243 if(s.successProperty){
244 v = this.getSuccess(o);
245 if(v === false || v === 'false'){
250 // TODO return Ext.data.Response instance instead. @see #readResponse
253 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
254 totalRecords : totalRecords
259 buildExtractors : function() {
263 var s = this.meta, Record = this.recordType,
264 f = Record.prototype.fields, fi = f.items, fl = f.length;
266 if(s.totalProperty) {
267 this.getTotal = this.createAccessor(s.totalProperty);
269 if(s.successProperty) {
270 this.getSuccess = this.createAccessor(s.successProperty);
272 if (s.messageProperty) {
273 this.getMessage = this.createAccessor(s.messageProperty);
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) {
280 return (r === undefined || r === '') ? null : r;
283 this.getId = function(){return null;};
286 for(var i = 0; i < fl; i++){
288 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
289 ef.push(this.createAccessor(map));
296 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
298 simpleAccess : function(obj, subsc) {
305 createAccessor : function(){
307 return function(expr) {
309 return(re.test(expr)) ?
310 new Function('obj', 'return obj.' + expr) :
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
325 extractData : function(root, returnRecords) {
327 if (this.isData(root)) {
330 if (Ext.isArray(root)) {
331 var f = this.recordType.prototype.fields,
335 if (returnRecords === true) {
336 var Record = this.recordType;
337 for (var i = 0; i < root.length; i++) {
339 var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
345 for (var i = 0; i < root.length; i++) {
346 rs.push(this.extractValues(root[i], fi, fl));
354 * type-casts a single row of raw-data from server
355 * @param {Object} data
356 * @param {Array} items
357 * @param {Integer} len
360 extractValues : function(data, items, len) {
362 for(var j = 0; j < len; j++){
364 var v = this.ef[j](data);
365 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
371 <div id="cls-Ext.data.JsonReader.Error"></div>/**
372 * @class Ext.data.JsonReader.Error
373 * Error class for JsonReader
375 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
376 constructor : function(message, arg) {
378 Ext.Error.call(this, message);
380 name : 'Ext.data.JsonReader'
382 Ext.apply(Ext.data.JsonReader.Error.prototype, {
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.'