1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.reader.Reader-method-constructor'><span id='Ext-data.reader.Reader'>/**
2 </span></span> * @author Ed Spencer
3 * @class Ext.data.reader.Reader
6 * <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}
7 * - usually in response to an AJAX request. This is normally handled transparently by passing some configuration to either the
8 * {@link Ext.data.Model Model} or the {@link Ext.data.Store Store} in question - see their documentation for further details.</p>
10 * <p><u>Loading Nested Data</u></p>
12 * <p>Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.Association associations}
13 * configured on each Model. Below is an example demonstrating the flexibility of these associations in a fictional CRM system which
14 * manages a User, their Orders, OrderItems and Products. First we'll define the models:
16 <pre><code>
17 Ext.define("User", {
18 extend: 'Ext.data.Model',
23 hasMany: {model: 'Order', name: 'orders'},
35 Ext.define("Order", {
36 extend: 'Ext.data.Model',
41 hasMany : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
45 Ext.define("OrderItem", {
46 extend: 'Ext.data.Model',
48 'id', 'price', 'quantity', 'order_id', 'product_id'
51 belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
54 Ext.define("Product", {
55 extend: 'Ext.data.Model',
62 </code></pre>
64 * <p>This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems. Finally,
65 * each OrderItem has a single Product. This allows us to consume data like this:</p>
67 <pre><code>
72 "name": "Ed",
76 "total": 100,
77 "order_items": [
80 "price" : 40,
81 "quantity": 2,
82 "product" : {
84 "name": "MacBook Pro"
89 "price" : 20,
90 "quantity": 3,
91 "product" : {
93 "name": "iPhone"
102 </code></pre>
104 * <p>The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the Orders
105 * for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case), and finally
106 * the Product associated with each OrderItem. Now we can read the data and use it as follows:
108 <pre><code>
109 var store = new Ext.data.Store({
110 model: "User"
114 callback: function() {
115 //the user that was loaded
116 var user = store.first();
118 console.log("Orders for " + user.get('name') + ":")
120 //iterate over the Orders for each User
121 user.orders().each(function(order) {
122 console.log("Order ID: " + order.getId() + ", which contains items:");
124 //iterate over the OrderItems for each Order
125 order.orderItems().each(function(orderItem) {
126 //we know that the Product data is already loaded, so we can use the synchronous getProduct
127 //usually, we would use the asynchronous version (see {@link Ext.data.BelongsToAssociation})
128 var product = orderItem.getProduct();
130 console.log(orderItem.get('quantity') + ' orders of ' + product.get('name'));
135 </code></pre>
137 * <p>Running the code above results in the following:</p>
139 <pre><code>
141 Order ID: 50, which contains items:
142 2 orders of MacBook Pro
144 </code></pre>
147 * @param {Object} config Optional config object
149 Ext.define('Ext.data.reader.Reader', {
150 requires: ['Ext.data.ResultSet'],
151 alternateClassName: ['Ext.data.Reader', 'Ext.data.DataReader'],
153 <span id='Ext-data.reader.Reader-cfg-idProperty'> /**
154 </span> * @cfg {String} idProperty Name of the property within a row object
155 * that contains a record identifier value. Defaults to <tt>The id of the model</tt>.
156 * If an idProperty is explicitly specified it will override that of the one specified
160 <span id='Ext-data.reader.Reader-cfg-totalProperty'> /**
161 </span> * @cfg {String} totalProperty Name of the property from which to
162 * retrieve the total number of records in the dataset. This is only needed
163 * if the whole dataset is not passed in one go, but is being paged from
164 * the remote server. Defaults to <tt>total</tt>.
166 totalProperty: 'total',
168 <span id='Ext-data.reader.Reader-cfg-successProperty'> /**
169 </span> * @cfg {String} successProperty Name of the property from which to
170 * retrieve the success attribute. Defaults to <tt>success</tt>. See
171 * {@link Ext.data.proxy.Proxy}.{@link Ext.data.proxy.Proxy#exception exception}
172 * for additional information.
174 successProperty: 'success',
176 <span id='Ext-data.reader.Reader-cfg-root'> /**
177 </span> * @cfg {String} root <b>Required</b>. The name of the property
178 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
179 * An exception will be thrown if the root property is undefined. The data
180 * packet value for this property should be an empty array to clear the data
185 <span id='Ext-data.reader.Reader-cfg-messageProperty'> /**
186 </span> * @cfg {String} messageProperty The name of the property which contains a response message.
187 * This property is optional.
190 <span id='Ext-data.reader.Reader-cfg-implicitIncludes'> /**
191 </span> * @cfg {Boolean} implicitIncludes True to automatically parse models nested within other models in a response
192 * object. See the Ext.data.reader.Reader intro docs for full explanation. Defaults to true.
194 implicitIncludes: true,
198 constructor: function(config) {
201 Ext.apply(me, config || {});
203 me.model = Ext.ModelManager.getModel(config.model);
205 me.buildExtractors();
209 <span id='Ext-data.reader.Reader-method-setModel'> /**
210 </span> * Sets a new model for the reader.
212 * @param {Object} model The model to set.
213 * @param {Boolean} setOnProxy True to also set on the Proxy, if one is configured
215 setModel: function(model, setOnProxy) {
218 me.model = Ext.ModelManager.getModel(model);
219 me.buildExtractors(true);
221 if (setOnProxy && me.proxy) {
222 me.proxy.setModel(me.model, true);
226 <span id='Ext-data.reader.Reader-method-read'> /**
227 </span> * Reads the given response object. This method normalizes the different types of response object that may be passed
228 * to it, before handing off the reading of records to the {@link #readRecords} function.
229 * @param {Object} response The response object. This may be either an XMLHttpRequest object or a plain JS object
230 * @return {Ext.data.ResultSet} The parsed ResultSet object
232 read: function(response) {
235 if (response && response.responseText) {
236 data = this.getResponseData(response);
240 return this.readRecords(data);
242 return this.nullResultSet;
246 <span id='Ext-data.reader.Reader-method-readRecords'> /**
247 </span> * Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call
248 * this function before running its own logic and returning the Ext.data.ResultSet instance. For most
249 * Readers additional processing should not be needed.
250 * @param {Mixed} data The raw data object
251 * @return {Ext.data.ResultSet} A ResultSet object
253 readRecords: function(data) {
257 * We check here whether the number of fields has changed since the last read.
258 * This works around an issue when a Model is used for both a Tree and another
259 * source, because the tree decorates the model with extra fields and it causes
260 * issues because the readers aren't notified.
262 if (me.fieldCount !== me.getFields().length) {
263 me.buildExtractors(true);
266 <span id='Ext-data.reader.Reader-property-rawData'> /**
267 </span> * The raw data object that was last passed to readRecords. Stored for further processing if needed
273 data = me.getData(data);
275 // If we pass an array as the data, we dont use getRoot on the data.
276 // Instead the root equals to the data.
277 var root = Ext.isArray(data) ? data : me.getRoot(data),
280 total, value, records, message;
286 if (me.totalProperty) {
287 value = parseInt(me.getTotal(data), 10);
293 if (me.successProperty) {
294 value = me.getSuccess(data);
295 if (value === false || value === 'false') {
300 if (me.messageProperty) {
301 message = me.getMessage(data);
305 records = me.extractData(root);
306 recordCount = records.length;
312 return Ext.create('Ext.data.ResultSet', {
313 total : total || recordCount,
321 <span id='Ext-data.reader.Reader-method-extractData'> /**
322 </span> * Returns extracted, type-cast rows of data. Iterates to call #extractValues for each row
323 * @param {Object[]/Object} data-root from server response
326 extractData : function(root) {
332 length = root.length,
333 idProp = me.getIdProperty(),
336 if (!root.length && Ext.isObject(root)) {
341 for (; i < length; i++) {
343 values = me.extractValues(node);
347 record = new Model(values, id);
349 records.push(record);
351 if (me.implicitIncludes) {
352 me.readAssociated(record, node);
359 <span id='Ext-data.reader.Reader-method-readAssociated'> /**
361 * Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations
362 * on the record provided.
363 * @param {Ext.data.Model} record The record to load associations for
364 * @param {Mixed} data The data object
365 * @return {String} Return value description
367 readAssociated: function(record, data) {
368 var associations = record.associations.items,
370 length = associations.length,
371 association, associationData, proxy, reader;
373 for (; i < length; i++) {
374 association = associations[i];
375 associationData = this.getAssociatedDataRoot(data, association.associationKey || association.name);
377 if (associationData) {
378 reader = association.getReader();
380 proxy = association.associatedModel.proxy;
381 // if the associated model has a Reader already, use that, otherwise attempt to create a sensible one
383 reader = proxy.getReader();
385 reader = new this.constructor({
386 model: association.associatedName
390 association.read(record, reader, associationData);
395 <span id='Ext-data.reader.Reader-method-getAssociatedDataRoot'> /**
397 * Used internally by {@link #readAssociated}. Given a data object (which could be json, xml etc) for a specific
398 * record, this should return the relevant part of that data for the given association name. This is only really
399 * needed to support the XML Reader, which has to do a query to get the associated data object
400 * @param {Mixed} data The raw data object
401 * @param {String} associationName The name of the association to get data for (uses associationKey if present)
402 * @return {Mixed} The root
404 getAssociatedDataRoot: function(data, associationName) {
405 return data[associationName];
408 getFields: function() {
409 return this.model.prototype.fields.items;
412 <span id='Ext-data.reader.Reader-method-extractValues'> /**
414 * Given an object representing a single model instance's data, iterates over the model's fields and
415 * builds an object with the value for each field.
416 * @param {Object} data The data object to convert
417 * @return {Object} Data object suitable for use with a model constructor
419 extractValues: function(data) {
420 var fields = this.getFields(),
422 length = fields.length,
426 for (; i < length; i++) {
428 value = this.extractorFunctions[i](data);
430 output[field.name] = value;
436 <span id='Ext-data.reader.Reader-method-getData'> /**
438 * By default this function just returns what is passed to it. It can be overridden in a subclass
439 * to return something else. See XmlReader for an example.
440 * @param {Object} data The data object
441 * @return {Object} The normalized data object
443 getData: function(data) {
447 <span id='Ext-data.reader.Reader-method-getRoot'> /**
449 * This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type
450 * of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config.
451 * See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.
452 * @param {Mixed} data The data object
453 * @return {Mixed} The same data object
455 getRoot: function(data) {
459 <span id='Ext-data.reader.Reader-method-getResponseData'> /**
460 </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
461 * @param {Object} response The responce object
462 * @return {Object} The useful data from the response
464 getResponseData: function(response) {
466 Ext.Error.raise("getResponseData must be implemented in the Ext.data.reader.Reader subclass");
470 <span id='Ext-data.reader.Reader-method-onMetaChange'> /**
472 * Reconfigures the meta data tied to this Reader
474 onMetaChange : function(meta) {
475 var fields = meta.fields,
478 Ext.apply(this, meta);
481 newModel = Ext.define("Ext.data.reader.Json-Model" + Ext.id(), {
482 extend: 'Ext.data.Model',
485 this.setModel(newModel, true);
487 this.buildExtractors(true);
491 <span id='Ext-data.reader.Reader-method-getIdProperty'> /**
492 </span> * Get the idProperty to use for extracting data
494 * @return {String} The id property
496 getIdProperty: function(){
497 var prop = this.idProperty;
498 if (Ext.isEmpty(prop)) {
499 prop = this.model.prototype.idProperty;
504 <span id='Ext-data.reader.Reader-method-buildExtractors'> /**
506 * This builds optimized functions for retrieving record data and meta data from an object.
507 * Subclasses may need to implement their own getRoot function.
508 * @param {Boolean} force True to automatically remove existing extractor functions first (defaults to false)
510 buildExtractors: function(force) {
512 idProp = me.getIdProperty(),
513 totalProp = me.totalProperty,
514 successProp = me.successProperty,
515 messageProp = me.messageProperty,
518 if (force === true) {
519 delete me.extractorFunctions;
522 if (me.extractorFunctions) {
526 //build the extractors for all the meta data
528 me.getTotal = me.createAccessor(totalProp);
532 me.getSuccess = me.createAccessor(successProp);
536 me.getMessage = me.createAccessor(messageProp);
540 accessor = me.createAccessor(idProp);
542 me.getId = function(record) {
543 var id = accessor.call(me, record);
544 return (id === undefined || id === '') ? null : id;
547 me.getId = function() {
551 me.buildFieldExtractors();
554 <span id='Ext-data.reader.Reader-method-buildFieldExtractors'> /**
557 buildFieldExtractors: function() {
558 //now build the extractors for all the fields
560 fields = me.getFields(),
563 extractorFunctions = [],
566 for (; i < ln; i++) {
568 map = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name;
570 extractorFunctions.push(me.createAccessor(map));
574 me.extractorFunctions = extractorFunctions;
578 // Private. Empty ResultSet to return when response is falsy (null|undefined|empty string)
579 nullResultSet: Ext.create('Ext.data.ResultSet', {
586 });</pre></pre></body></html>