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>
8 <body onload="prettyPrint();">
9 <pre class="prettyprint lang-js">/*!
10 * Ext JS Library 3.2.1
11 * Copyright(c) 2006-2010 Ext JS, Inc.
13 * http://www.extjs.com/license
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}
21 * <p>Example code:</p>
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)
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's 'firstname' field to data object's key of same name
35 // map Record's 'job' field to data object's 'occupation' key
36 {name: 'job', mapping: 'occupation'}
40 * <p>This would consume a JSON data object of the form:</p><pre><code>
42 results: 2000, // Reader's configured {@link #totalProperty}
43 rows: [ // Reader'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' },
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();
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>
69 "{@link #idProperty}": "id",
70 "{@link #root}": "rows",
71 "{@link #totalProperty}": "results"
72 "{@link #successProperty}": "success",
73 "{@link Ext.data.DataReader#fields fields}": [
75 {"name": "job", "mapping": "occupation"}
77 // used by store to set its sortInfo
82 // {@link Ext.PagingToolbar paging data} (if applicable)
88 // Reader's configured {@link #successProperty}
90 // Reader's configured {@link #totalProperty}
92 // Reader'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" }
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>
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>
121 Ext.data.JsonReader = function(meta, recordType){
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>
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.
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>.
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
148 successProperty: 'success',
149 totalProperty: 'total'
152 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
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.
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.
167 read : function(response){
168 var json = response.responseText;
169 var o = Ext.decode(json);
171 throw {message: 'JsonReader.read: Json object not found'};
173 return this.readRecords(o);
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.
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.
186 readResponse : function(action, response) {
187 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
189 throw new Ext.data.JsonReader.Error('response');
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);
199 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
203 // instantiate response object
204 var res = new Ext.data.Response({
206 success: this.getSuccess(o),
207 data: (root) ? this.extractData(root, false) : [],
208 message: this.getMessage(o),
212 // blow up if no successProperty
213 if (Ext.isEmpty(res.success)) {
214 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
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.
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.
235 this.onMetaChange(o.metaData);
237 var s = this.meta, Record = this.recordType,
238 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
240 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
242 v = parseInt(this.getTotal(o), 10);
247 if(s.successProperty){
248 v = this.getSuccess(o);
249 if(v === false || v === 'false'){
254 // TODO return Ext.data.Response instance instead. @see #readResponse
257 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
258 totalRecords : totalRecords
263 buildExtractors : function() {
267 var s = this.meta, Record = this.recordType,
268 f = Record.prototype.fields, fi = f.items, fl = f.length;
270 if(s.totalProperty) {
271 this.getTotal = this.createAccessor(s.totalProperty);
273 if(s.successProperty) {
274 this.getSuccess = this.createAccessor(s.successProperty);
276 if (s.messageProperty) {
277 this.getMessage = this.createAccessor(s.messageProperty);
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) {
284 return (r === undefined || r === '') ? null : r;
287 this.getId = function(){return null;};
290 for(var i = 0; i < fl; i++){
292 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
293 ef.push(this.createAccessor(map));
300 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
302 simpleAccess : function(obj, subsc) {
309 createAccessor : function(){
311 return function(expr) {
312 if(Ext.isEmpty(expr)){
315 if(Ext.isFunction(expr)){
318 var i = String(expr).search(re);
320 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
322 return function(obj){
330 * type-casts a single row of raw-data from server
331 * @param {Object} data
332 * @param {Array} items
333 * @param {Integer} len
336 extractValues : function(data, items, len) {
338 for(var j = 0; j < len; j++){
340 var v = this.ef[j](data);
341 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
347 <div id="cls-Ext.data.JsonReader.Error"></div>/**
348 * @class Ext.data.JsonReader.Error
349 * Error class for JsonReader
351 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
352 constructor : function(message, arg) {
354 Ext.Error.call(this, message);
356 name : 'Ext.data.JsonReader'
358 Ext.apply(Ext.data.JsonReader.Error.prototype, {
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.'