3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
\r
4 <title>The source code</title>
\r
5 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
\r
6 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
\r
8 <body onload="prettyPrint();">
\r
9 <pre class="prettyprint lang-js"><div id="cls-Ext.data.JsonReader"></div>/**
10 * @class Ext.data.JsonReader
11 * @extends Ext.data.DataReader
12 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
13 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
15 * <p>Example code:</p>
17 var myReader = new Ext.data.JsonReader({
18 // metadata configuration options:
19 {@link #idProperty}: 'id'
20 {@link #root}: 'rows',
21 {@link #totalProperty}: 'results',
22 {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
24 // the fields config option will internally create an {@link Ext.data.Record}
25 // constructor that provides mapping for reading the record data objects
26 {@link Ext.data.DataReader#fields fields}: [
27 // map Record's 'firstname' field to data object's key of same name
29 // map Record's 'job' field to data object's 'occupation' key
30 {name: 'job', mapping: 'occupation'}
34 * <p>This would consume a JSON data object of the form:</p><pre><code>
36 results: 2000, // Reader's configured {@link #totalProperty}
37 rows: [ // Reader's configured {@link #root}
38 // record data objects:
39 { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
40 { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
45 * <p><b><u>Automatic configuration using metaData</u></b></p>
46 * <p>It is possible to change a JsonReader's metadata at any time by including
47 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
48 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
49 * object using this Reader will reconfigure itself to use the newly provided
50 * field definition and fire its {@link Ext.data.Store#metachange metachange}
51 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
52 * property to perform any configuration required.</p>
53 * <p>Note that reconfiguring a Store potentially invalidates objects which may
54 * refer to Fields or Records which no longer exist.</p>
55 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
56 var myReader = new Ext.data.JsonReader();
58 * <p>The first data packet from the server would configure the reader by
59 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
60 * example, the JSON data object might take the form:</p><pre><code>
63 "{@link #idProperty}": "id",
64 "{@link #root}": "rows",
65 "{@link #totalProperty}": "results"
66 "{@link #successProperty}": "success",
67 "{@link Ext.data.DataReader#fields fields}": [
69 {"name": "job", "mapping": "occupation"}
71 // used by store to set its sortInfo
76 // {@link Ext.PagingToolbar paging data} (if applicable)
82 // Reader's configured {@link #successProperty}
84 // Reader's configured {@link #totalProperty}
86 // Reader's configured {@link #root}
87 // (this data simulates 2 results {@link Ext.PagingToolbar per page})
88 "rows": [ // <b>*Note:</b> this must be an Array
89 { "id": 1, "name": "Bill", "occupation": "Gardener" },
90 { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
94 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
95 * <div class="mdetail-params"><ul>
96 * <li>any of the configuration options for this class</li>
97 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
98 * the JsonReader will use as an argument to the
99 * {@link Ext.data.Record#create data Record create method} in order to
100 * configure the layout of the Records it will produce.</li>
101 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
102 * which the JsonReader will use to set the {@link Ext.data.Store}'s
103 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
104 * <li>any custom properties needed</li>
108 * Create a new JsonReader
109 * @param {Object} meta Metadata configuration options.
110 * @param {Array/Object} recordType
111 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
112 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
113 * constructor created from {@link Ext.data.Record#create}.</p>
115 Ext.data.JsonReader = function(meta, recordType){
117 <div id="cfg-Ext.data.JsonReader-idProperty"></div>/**
118 * @cfg {String} idProperty [id] Name of the property within a row object
119 * that contains a record identifier value. Defaults to <tt>id</tt>
121 <div id="cfg-Ext.data.JsonReader-successProperty"></div>/**
122 * @cfg {String} successProperty [success] Name of the property from which to
123 * retrieve the success attribute. Defaults to <tt>success</tt>. See
124 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
125 * for additional information.
127 <div id="cfg-Ext.data.JsonReader-totalProperty"></div>/**
128 * @cfg {String} totalProperty [total] Name of the property from which to
129 * retrieve the total number of records in the dataset. This is only needed
130 * if the whole dataset is not passed in one go, but is being paged from
131 * the remote server. Defaults to <tt>total</tt>.
133 <div id="cfg-Ext.data.JsonReader-root"></div>/**
134 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
135 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
136 * An exception will be thrown if the root property is undefined. The data
137 * packet value for this property should be an empty array to clear the data
142 successProperty: 'success',
143 totalProperty: 'total'
146 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
148 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
149 <div id="prop-Ext.data.JsonReader-meta"></div>/**
150 * This JsonReader's metadata as passed to the constructor, or as passed in
151 * the last data packet's <b><tt>metaData</tt></b> property.
155 <div id="method-Ext.data.JsonReader-read"></div>/**
156 * This method is only used by a DataProxy which has retrieved data from a remote server.
157 * @param {Object} response The XHR object which contains the JSON data in its responseText.
158 * @return {Object} data A data block which is used by an Ext.data.Store object as
159 * a cache of Ext.data.Records.
161 read : function(response){
162 var json = response.responseText;
163 var o = Ext.decode(json);
165 throw {message: 'JsonReader.read: Json object not found'};
167 return this.readRecords(o);
170 <div id="method-Ext.data.JsonReader-readResponse"></div>/**
171 * Decode a json response from server.
172 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
173 * @param {Object} response
174 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
175 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
177 readResponse : function(action, response) {
178 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
180 throw new Ext.data.JsonReader.Error('response');
183 var root = this.getRoot(o);
184 if (action === Ext.data.Api.actions.create) {
185 var def = Ext.isDefined(root);
186 if (def && Ext.isEmpty(root)) {
187 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
190 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
194 // instantiate response object
195 var res = new Ext.data.Response({
197 success: this.getSuccess(o),
198 data: (root) ? this.extractData(root, false) : [],
199 message: this.getMessage(o),
203 // blow up if no successProperty
204 if (Ext.isEmpty(res.success)) {
205 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
210 <div id="method-Ext.data.JsonReader-readRecords"></div>/**
211 * Create a data block containing Ext.data.Records from a JSON object.
212 * @param {Object} o An object which contains an Array of row objects in the property specified
213 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
214 * which contains the total size of the dataset.
215 * @return {Object} data A data block which is used by an Ext.data.Store object as
216 * a cache of Ext.data.Records.
218 readRecords : function(o){
219 <div id="prop-Ext.data.JsonReader-jsonData"></div>/**
220 * After any data loads, the raw JSON data is available for further custom processing. If no data is
221 * loaded or there is a load exception this property will be undefined.
226 this.onMetaChange(o.metaData);
228 var s = this.meta, Record = this.recordType,
229 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
231 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
233 v = parseInt(this.getTotal(o), 10);
238 if(s.successProperty){
239 v = this.getSuccess(o);
240 if(v === false || v === 'false'){
245 // TODO return Ext.data.Response instance instead. @see #readResponse
248 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
249 totalRecords : totalRecords
254 buildExtractors : function() {
258 var s = this.meta, Record = this.recordType,
259 f = Record.prototype.fields, fi = f.items, fl = f.length;
261 if(s.totalProperty) {
262 this.getTotal = this.createAccessor(s.totalProperty);
264 if(s.successProperty) {
265 this.getSuccess = this.createAccessor(s.successProperty);
267 if (s.messageProperty) {
268 this.getMessage = this.createAccessor(s.messageProperty);
270 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
271 if (s.id || s.idProperty) {
272 var g = this.createAccessor(s.id || s.idProperty);
273 this.getId = function(rec) {
275 return (r === undefined || r === '') ? null : r;
278 this.getId = function(){return null;};
281 for(var i = 0; i < fl; i++){
283 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
284 ef.push(this.createAccessor(map));
291 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
293 simpleAccess : function(obj, subsc) {
300 createAccessor : function(){
302 return function(expr) {
303 if(Ext.isEmpty(expr)){
306 if(Ext.isFunction(expr)){
309 var i = String(expr).search(re);
311 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
313 return function(obj){
321 * type-casts a single row of raw-data from server
322 * @param {Object} data
323 * @param {Array} items
324 * @param {Integer} len
327 extractValues : function(data, items, len) {
329 for(var j = 0; j < len; j++){
331 var v = this.ef[j](data);
332 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
338 <div id="cls-Ext.data.JsonReader.Error"></div>/**
339 * @class Ext.data.JsonReader.Error
340 * Error class for JsonReader
342 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
343 constructor : function(message, arg) {
345 Ext.Error.call(this, message);
347 name : 'Ext.data.JsonReader'
349 Ext.apply(Ext.data.JsonReader.Error.prototype, {
351 'response': 'An error occurred while json-decoding your server response',
352 '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.',
353 '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.',
354 '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.',
355 '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.'