4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-data-reader-Reader-method-constructor'><span id='Ext-data-reader-Reader'>/**
19 </span></span> * @author Ed Spencer
20 * @class Ext.data.reader.Reader
23 * <p>Readers are used to interpret data to be loaded into a {@link Ext.data.Model Model} instance or a {@link Ext.data.Store Store}
24 * - usually in response to an AJAX request. This is normally handled transparently by passing some configuration to either the
25 * {@link Ext.data.Model Model} or the {@link Ext.data.Store Store} in question - see their documentation for further details.</p>
27 * <p><u>Loading Nested Data</u></p>
29 * <p>Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.Association associations}
30 * configured on each Model. Below is an example demonstrating the flexibility of these associations in a fictional CRM system which
31 * manages a User, their Orders, OrderItems and Products. First we'll define the models:
33 <pre><code>
34 Ext.define("User", {
35 extend: 'Ext.data.Model',
40 hasMany: {model: 'Order', name: 'orders'},
52 Ext.define("Order", {
53 extend: 'Ext.data.Model',
58 hasMany : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
62 Ext.define("OrderItem", {
63 extend: 'Ext.data.Model',
65 'id', 'price', 'quantity', 'order_id', 'product_id'
68 belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
71 Ext.define("Product", {
72 extend: 'Ext.data.Model',
79 </code></pre>
81 * <p>This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems. Finally,
82 * each OrderItem has a single Product. This allows us to consume data like this:</p>
84 <pre><code>
89 "name": "Ed",
93 "total": 100,
94 "order_items": [
97 "price" : 40,
98 "quantity": 2,
99 "product" : {
100 "id": 1000,
101 "name": "MacBook Pro"
106 "price" : 20,
107 "quantity": 3,
108 "product" : {
109 "id": 1001,
110 "name": "iPhone"
119 </code></pre>
121 * <p>The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the Orders
122 * for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case), and finally
123 * the Product associated with each OrderItem. Now we can read the data and use it as follows:
125 <pre><code>
126 var store = new Ext.data.Store({
127 model: "User"
131 callback: function() {
132 //the user that was loaded
133 var user = store.first();
135 console.log("Orders for " + user.get('name') + ":")
137 //iterate over the Orders for each User
138 user.orders().each(function(order) {
139 console.log("Order ID: " + order.getId() + ", which contains items:");
141 //iterate over the OrderItems for each Order
142 order.orderItems().each(function(orderItem) {
143 //we know that the Product data is already loaded, so we can use the synchronous getProduct
144 //usually, we would use the asynchronous version (see {@link Ext.data.BelongsToAssociation})
145 var product = orderItem.getProduct();
147 console.log(orderItem.get('quantity') + ' orders of ' + product.get('name'));
152 </code></pre>
154 * <p>Running the code above results in the following:</p>
156 <pre><code>
158 Order ID: 50, which contains items:
159 2 orders of MacBook Pro
161 </code></pre>
164 * @param {Object} config Optional config object
166 Ext.define('Ext.data.reader.Reader', {
167 requires: ['Ext.data.ResultSet'],
168 alternateClassName: ['Ext.data.Reader', 'Ext.data.DataReader'],
170 <span id='Ext-data-reader-Reader-cfg-idProperty'> /**
171 </span> * @cfg {String} idProperty Name of the property within a row object
172 * that contains a record identifier value. Defaults to <tt>The id of the model</tt>.
173 * If an idProperty is explicitly specified it will override that of the one specified
177 <span id='Ext-data-reader-Reader-cfg-totalProperty'> /**
178 </span> * @cfg {String} totalProperty Name of the property from which to
179 * retrieve the total number of records in the dataset. This is only needed
180 * if the whole dataset is not passed in one go, but is being paged from
181 * the remote server. Defaults to <tt>total</tt>.
183 totalProperty: 'total',
185 <span id='Ext-data-reader-Reader-cfg-successProperty'> /**
186 </span> * @cfg {String} successProperty Name of the property from which to
187 * retrieve the success attribute. Defaults to <tt>success</tt>. See
188 * {@link Ext.data.proxy.Proxy}.{@link Ext.data.proxy.Proxy#exception exception}
189 * for additional information.
191 successProperty: 'success',
193 <span id='Ext-data-reader-Reader-cfg-root'> /**
194 </span> * @cfg {String} root <b>Required</b>. The name of the property
195 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
196 * An exception will be thrown if the root property is undefined. The data
197 * packet value for this property should be an empty array to clear the data
202 <span id='Ext-data-reader-Reader-cfg-messageProperty'> /**
203 </span> * @cfg {String} messageProperty The name of the property which contains a response message.
204 * This property is optional.
207 <span id='Ext-data-reader-Reader-cfg-implicitIncludes'> /**
208 </span> * @cfg {Boolean} implicitIncludes True to automatically parse models nested within other models in a response
209 * object. See the Ext.data.reader.Reader intro docs for full explanation. Defaults to true.
211 implicitIncludes: true,
215 constructor: function(config) {
218 Ext.apply(me, config || {});
220 me.model = Ext.ModelManager.getModel(config.model);
222 me.buildExtractors();
226 <span id='Ext-data-reader-Reader-method-setModel'> /**
227 </span> * Sets a new model for the reader.
229 * @param {Object} model The model to set.
230 * @param {Boolean} setOnProxy True to also set on the Proxy, if one is configured
232 setModel: function(model, setOnProxy) {
235 me.model = Ext.ModelManager.getModel(model);
236 me.buildExtractors(true);
238 if (setOnProxy && me.proxy) {
239 me.proxy.setModel(me.model, true);
243 <span id='Ext-data-reader-Reader-method-read'> /**
244 </span> * Reads the given response object. This method normalizes the different types of response object that may be passed
245 * to it, before handing off the reading of records to the {@link #readRecords} function.
246 * @param {Object} response The response object. This may be either an XMLHttpRequest object or a plain JS object
247 * @return {Ext.data.ResultSet} The parsed ResultSet object
249 read: function(response) {
252 if (response && response.responseText) {
253 data = this.getResponseData(response);
257 return this.readRecords(data);
259 return this.nullResultSet;
263 <span id='Ext-data-reader-Reader-method-readRecords'> /**
264 </span> * Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call
265 * this function before running its own logic and returning the Ext.data.ResultSet instance. For most
266 * Readers additional processing should not be needed.
267 * @param {Mixed} data The raw data object
268 * @return {Ext.data.ResultSet} A ResultSet object
270 readRecords: function(data) {
274 * We check here whether the number of fields has changed since the last read.
275 * This works around an issue when a Model is used for both a Tree and another
276 * source, because the tree decorates the model with extra fields and it causes
277 * issues because the readers aren't notified.
279 if (me.fieldCount !== me.getFields().length) {
280 me.buildExtractors(true);
283 <span id='Ext-data-reader-Reader-property-rawData'> /**
284 </span> * The raw data object that was last passed to readRecords. Stored for further processing if needed
290 data = me.getData(data);
292 // If we pass an array as the data, we dont use getRoot on the data.
293 // Instead the root equals to the data.
294 var root = Ext.isArray(data) ? data : me.getRoot(data),
297 total, value, records, message;
303 if (me.totalProperty) {
304 value = parseInt(me.getTotal(data), 10);
310 if (me.successProperty) {
311 value = me.getSuccess(data);
312 if (value === false || value === 'false') {
317 if (me.messageProperty) {
318 message = me.getMessage(data);
322 records = me.extractData(root);
323 recordCount = records.length;
329 return Ext.create('Ext.data.ResultSet', {
330 total : total || recordCount,
338 <span id='Ext-data-reader-Reader-method-extractData'> /**
339 </span> * Returns extracted, type-cast rows of data. Iterates to call #extractValues for each row
340 * @param {Object[]/Object} data-root from server response
343 extractData : function(root) {
349 length = root.length,
350 idProp = me.getIdProperty(),
353 if (!root.length && Ext.isObject(root)) {
358 for (; i < length; i++) {
360 values = me.extractValues(node);
364 record = new Model(values, id, node);
365 records.push(record);
367 if (me.implicitIncludes) {
368 me.readAssociated(record, node);
375 <span id='Ext-data-reader-Reader-method-readAssociated'> /**
377 * Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations
378 * on the record provided.
379 * @param {Ext.data.Model} record The record to load associations for
380 * @param {Mixed} data The data object
381 * @return {String} Return value description
383 readAssociated: function(record, data) {
384 var associations = record.associations.items,
386 length = associations.length,
387 association, associationData, proxy, reader;
389 for (; i < length; i++) {
390 association = associations[i];
391 associationData = this.getAssociatedDataRoot(data, association.associationKey || association.name);
393 if (associationData) {
394 reader = association.getReader();
396 proxy = association.associatedModel.proxy;
397 // if the associated model has a Reader already, use that, otherwise attempt to create a sensible one
399 reader = proxy.getReader();
401 reader = new this.constructor({
402 model: association.associatedName
406 association.read(record, reader, associationData);
411 <span id='Ext-data-reader-Reader-method-getAssociatedDataRoot'> /**
413 * Used internally by {@link #readAssociated}. Given a data object (which could be json, xml etc) for a specific
414 * record, this should return the relevant part of that data for the given association name. This is only really
415 * needed to support the XML Reader, which has to do a query to get the associated data object
416 * @param {Mixed} data The raw data object
417 * @param {String} associationName The name of the association to get data for (uses associationKey if present)
418 * @return {Mixed} The root
420 getAssociatedDataRoot: function(data, associationName) {
421 return data[associationName];
424 getFields: function() {
425 return this.model.prototype.fields.items;
428 <span id='Ext-data-reader-Reader-method-extractValues'> /**
430 * Given an object representing a single model instance's data, iterates over the model's fields and
431 * builds an object with the value for each field.
432 * @param {Object} data The data object to convert
433 * @return {Object} Data object suitable for use with a model constructor
435 extractValues: function(data) {
436 var fields = this.getFields(),
438 length = fields.length,
442 for (; i < length; i++) {
444 value = this.extractorFunctions[i](data);
446 output[field.name] = value;
452 <span id='Ext-data-reader-Reader-method-getData'> /**
454 * By default this function just returns what is passed to it. It can be overridden in a subclass
455 * to return something else. See XmlReader for an example.
456 * @param {Object} data The data object
457 * @return {Object} The normalized data object
459 getData: function(data) {
463 <span id='Ext-data-reader-Reader-method-getRoot'> /**
465 * This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type
466 * of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config.
467 * See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.
468 * @param {Mixed} data The data object
469 * @return {Mixed} The same data object
471 getRoot: function(data) {
475 <span id='Ext-data-reader-Reader-method-getResponseData'> /**
476 </span> * Takes a raw response object (as passed to this.read) and returns the useful data segment of it. This must be implemented by each subclass
477 * @param {Object} response The responce object
478 * @return {Object} The useful data from the response
480 getResponseData: function(response) {
482 Ext.Error.raise("getResponseData must be implemented in the Ext.data.reader.Reader subclass");
486 <span id='Ext-data-reader-Reader-method-onMetaChange'> /**
488 * Reconfigures the meta data tied to this Reader
490 onMetaChange : function(meta) {
491 var fields = meta.fields,
494 Ext.apply(this, meta);
497 newModel = Ext.define("Ext.data.reader.Json-Model" + Ext.id(), {
498 extend: 'Ext.data.Model',
501 this.setModel(newModel, true);
503 this.buildExtractors(true);
507 <span id='Ext-data-reader-Reader-method-getIdProperty'> /**
508 </span> * Get the idProperty to use for extracting data
510 * @return {String} The id property
512 getIdProperty: function(){
513 var prop = this.idProperty;
514 if (Ext.isEmpty(prop)) {
515 prop = this.model.prototype.idProperty;
520 <span id='Ext-data-reader-Reader-method-buildExtractors'> /**
522 * This builds optimized functions for retrieving record data and meta data from an object.
523 * Subclasses may need to implement their own getRoot function.
524 * @param {Boolean} force True to automatically remove existing extractor functions first (defaults to false)
526 buildExtractors: function(force) {
528 idProp = me.getIdProperty(),
529 totalProp = me.totalProperty,
530 successProp = me.successProperty,
531 messageProp = me.messageProperty,
534 if (force === true) {
535 delete me.extractorFunctions;
538 if (me.extractorFunctions) {
542 //build the extractors for all the meta data
544 me.getTotal = me.createAccessor(totalProp);
548 me.getSuccess = me.createAccessor(successProp);
552 me.getMessage = me.createAccessor(messageProp);
556 accessor = me.createAccessor(idProp);
558 me.getId = function(record) {
559 var id = accessor.call(me, record);
560 return (id === undefined || id === '') ? null : id;
563 me.getId = function() {
567 me.buildFieldExtractors();
570 <span id='Ext-data-reader-Reader-method-buildFieldExtractors'> /**
573 buildFieldExtractors: function() {
574 //now build the extractors for all the fields
576 fields = me.getFields(),
579 extractorFunctions = [],
582 for (; i < ln; i++) {
584 map = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name;
586 extractorFunctions.push(me.createAccessor(map));
590 me.extractorFunctions = extractorFunctions;
594 // Private. Empty ResultSet to return when response is falsy (null|undefined|empty string)
595 nullResultSet: Ext.create('Ext.data.ResultSet', {