Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / data / reader / Array.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.reader.Array
4  * @extends Ext.data.reader.Json
5  * 
6  * <p>Data reader class to create an Array of {@link Ext.data.Model} objects from an Array.
7  * Each element of that Array represents a row of data fields. The
8  * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
9  * of the field definition if it exists, or the field's ordinal position in the definition.</p>
10  * 
11  * <p><u>Example code:</u></p>
12  * 
13 <pre><code>
14 Employee = Ext.define('Employee', {
15     extend: 'Ext.data.Model',
16     fields: [
17         'id',
18         {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
19         {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.        
20     ]
21 });
22
23 var myReader = new Ext.data.reader.Array({
24     model: 'Employee'
25 }, Employee);
26 </code></pre>
27  * 
28  * <p>This would consume an Array like this:</p>
29  * 
30 <pre><code>
31 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
32 </code></pre>
33  * 
34  * @constructor
35  * Create a new ArrayReader
36  * @param {Object} meta Metadata configuration options.
37  */
38 Ext.define('Ext.data.reader.Array', {
39     extend: 'Ext.data.reader.Json',
40     alternateClassName: 'Ext.data.ArrayReader',
41     alias : 'reader.array',
42
43     /**
44      * @private
45      * Most of the work is done for us by JsonReader, but we need to overwrite the field accessors to just
46      * reference the correct position in the array.
47      */
48     buildExtractors: function() {
49         this.callParent(arguments);
50         
51         var fields = this.model.prototype.fields.items,
52             length = fields.length,
53             extractorFunctions = [],
54             i;
55         
56         for (i = 0; i < length; i++) {
57             extractorFunctions.push(function(index) {
58                 return function(data) {
59                     return data[index];
60                 };
61             }(fields[i].mapping || i));
62         }
63         
64         this.extractorFunctions = extractorFunctions;
65     }
66 });