Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / pkgs / data-foundation-debug.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.Api
9  * @extends Object
10  * Ext.data.Api is a singleton designed to manage the data API including methods
11  * for validating a developer's DataProxy API.  Defines variables for CRUD actions
12  * create, read, update and destroy in addition to a mapping of RESTful HTTP methods
13  * GET, POST, PUT and DELETE to CRUD actions.
14  * @singleton
15  */
16 Ext.data.Api = (function() {
17
18     // private validActions.  validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
19     // Some methods in this singleton (e.g.: getActions, getVerb) will loop through actions with the code <code>for (var verb in this.actions)</code>
20     // For efficiency, some methods will first check this hash for a match.  Those methods which do acces validActions will cache their result here.
21     // We cannot pre-define this hash since the developer may over-ride the actions at runtime.
22     var validActions = {};
23
24     return {
25         /**
26          * Defined actions corresponding to remote actions:
27          * <pre><code>
28 actions: {
29     create  : 'create',  // Text representing the remote-action to create records on server.
30     read    : 'read',    // Text representing the remote-action to read/load data from server.
31     update  : 'update',  // Text representing the remote-action to update records on server.
32     destroy : 'destroy'  // Text representing the remote-action to destroy records on server.
33 }
34          * </code></pre>
35          * @property actions
36          * @type Object
37          */
38         actions : {
39             create  : 'create',
40             read    : 'read',
41             update  : 'update',
42             destroy : 'destroy'
43         },
44
45         /**
46          * Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
47          * corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
48          * Defaults to:
49          * <pre><code>
50 restActions : {
51     create  : 'POST',
52     read    : 'GET',
53     update  : 'PUT',
54     destroy : 'DELETE'
55 },
56          * </code></pre>
57          */
58         restActions : {
59             create  : 'POST',
60             read    : 'GET',
61             update  : 'PUT',
62             destroy : 'DELETE'
63         },
64
65         /**
66          * Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
67          * @param {String} action
68          * @param {String[]}(Optional) List of available CRUD actions.  Pass in list when executing multiple times for efficiency.
69          * @return {Boolean}
70          */
71         isAction : function(action) {
72             return (Ext.data.Api.actions[action]) ? true : false;
73         },
74
75         /**
76          * Returns the actual CRUD action KEY "create", "read", "update" or "destroy" from the supplied action-name.  This method is used internally and shouldn't generally
77          * need to be used directly.  The key/value pair of Ext.data.Api.actions will often be identical but this is not necessarily true.  A developer can override this naming
78          * convention if desired.  However, the framework internally calls methods based upon the KEY so a way of retreiving the the words "create", "read", "update" and "destroy" is
79          * required.  This method will cache discovered KEYS into the private validActions hash.
80          * @param {String} name The runtime name of the action.
81          * @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
82          * @nodoc
83          */
84         getVerb : function(name) {
85             if (validActions[name]) {
86                 return validActions[name];  // <-- found in cache.  return immediately.
87             }
88             for (var verb in this.actions) {
89                 if (this.actions[verb] === name) {
90                     validActions[name] = verb;
91                     break;
92                 }
93             }
94             return (validActions[name] !== undefined) ? validActions[name] : null;
95         },
96
97         /**
98          * Returns true if the supplied API is valid; that is, check that all keys match defined actions
99          * otherwise returns an array of mistakes.
100          * @return {String[]||true}
101          */
102         isValid : function(api){
103             var invalid = [];
104             var crud = this.actions; // <-- cache a copy of the actions.
105             for (var action in api) {
106                 if (!(action in crud)) {
107                     invalid.push(action);
108                 }
109             }
110             return (!invalid.length) ? true : invalid;
111         },
112
113         /**
114          * Returns true if the supplied verb upon the supplied proxy points to a unique url in that none of the other api-actions
115          * point to the same url.  The question is important for deciding whether to insert the "xaction" HTTP parameter within an
116          * Ajax request.  This method is used internally and shouldn't generally need to be called directly.
117          * @param {Ext.data.DataProxy} proxy
118          * @param {String} verb
119          * @return {Boolean}
120          */
121         hasUniqueUrl : function(proxy, verb) {
122             var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
123             var unique = true;
124             for (var action in proxy.api) {
125                 if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
126                     break;
127                 }
128             }
129             return unique;
130         },
131
132         /**
133          * This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
134          * Each action of a DataProxy api can be initially defined as either a String or an Object.  When specified as an object,
135          * one can explicitly define the HTTP method (GET|POST) to use for each CRUD action.  This method will prepare the supplied API, setting
136          * each action to the Object form.  If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
137          * be used.  If the method configuration parameter is not specified, POST will be used.
138          <pre><code>
139 new Ext.data.HttpProxy({
140     method: "POST",     // <-- default HTTP method when not specified.
141     api: {
142         create: 'create.php',
143         load: 'read.php',
144         save: 'save.php',
145         destroy: 'destroy.php'
146     }
147 });
148
149 // Alternatively, one can use the object-form to specify the API
150 new Ext.data.HttpProxy({
151     api: {
152         load: {url: 'read.php', method: 'GET'},
153         create: 'create.php',
154         destroy: 'destroy.php',
155         save: 'update.php'
156     }
157 });
158         </code></pre>
159          *
160          * @param {Ext.data.DataProxy} proxy
161          */
162         prepare : function(proxy) {
163             if (!proxy.api) {
164                 proxy.api = {}; // <-- No api?  create a blank one.
165             }
166             for (var verb in this.actions) {
167                 var action = this.actions[verb];
168                 proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
169                 if (typeof(proxy.api[action]) == 'string') {
170                     proxy.api[action] = {
171                         url: proxy.api[action]
172                     };
173                 }
174             }
175         },
176
177         /**
178          * Prepares a supplied Proxy to be RESTful.  Sets the HTTP method for each api-action to be one of
179          * GET, POST, PUT, DELETE according to the defined {@link #restActions}.
180          * @param {Ext.data.DataProxy} proxy
181          */
182         restify : function(proxy) {
183             proxy.restful = true;
184             for (var verb in this.restActions) {
185                 proxy.api[this.actions[verb]].method = this.restActions[verb];
186             }
187         }
188     };
189 })();
190
191 /**
192  * @class Ext.data.Api.Error
193  * @extends Ext.Error
194  * Error class for Ext.data.Api errors
195  */
196 Ext.data.Api.Error = Ext.extend(Ext.Error, {
197     constructor : function(message, arg) {
198         this.arg = arg;
199         Ext.Error.call(this, message);
200     },
201     name: 'Ext.data.Api'
202 });
203 Ext.apply(Ext.data.Api.Error.prototype, {
204     lang: {
205         'action-url-undefined': 'No fallback url defined for this action.  When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.',
206         'invalid': 'received an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
207         'invalid-url': 'Invalid url.  Please review your proxy configuration.',
208         'execute': 'Attempted to execute an unknown action.  Valid API actions are defined in Ext.data.Api.actions"'
209     }
210 });
211 \r
212 /**\r
213  * @class Ext.data.SortTypes\r
214  * @singleton\r
215  * Defines the default sorting (casting?) comparison functions used when sorting data.\r
216  */\r
217 Ext.data.SortTypes = {\r
218     /**\r
219      * Default sort that does nothing\r
220      * @param {Mixed} s The value being converted\r
221      * @return {Mixed} The comparison value\r
222      */\r
223     none : function(s){\r
224         return s;\r
225     },\r
226     \r
227     /**\r
228      * The regular expression used to strip tags\r
229      * @type {RegExp}\r
230      * @property\r
231      */\r
232     stripTagsRE : /<\/?[^>]+>/gi,\r
233     \r
234     /**\r
235      * Strips all HTML tags to sort on text only\r
236      * @param {Mixed} s The value being converted\r
237      * @return {String} The comparison value\r
238      */\r
239     asText : function(s){\r
240         return String(s).replace(this.stripTagsRE, "");\r
241     },\r
242     \r
243     /**\r
244      * Strips all HTML tags to sort on text only - Case insensitive\r
245      * @param {Mixed} s The value being converted\r
246      * @return {String} The comparison value\r
247      */\r
248     asUCText : function(s){\r
249         return String(s).toUpperCase().replace(this.stripTagsRE, "");\r
250     },\r
251     \r
252     /**\r
253      * Case insensitive string\r
254      * @param {Mixed} s The value being converted\r
255      * @return {String} The comparison value\r
256      */\r
257     asUCString : function(s) {\r
258         return String(s).toUpperCase();\r
259     },\r
260     \r
261     /**\r
262      * Date sorting\r
263      * @param {Mixed} s The value being converted\r
264      * @return {Number} The comparison value\r
265      */\r
266     asDate : function(s) {\r
267         if(!s){\r
268             return 0;\r
269         }\r
270         if(Ext.isDate(s)){\r
271             return s.getTime();\r
272         }\r
273         return Date.parse(String(s));\r
274     },\r
275     \r
276     /**\r
277      * Float sorting\r
278      * @param {Mixed} s The value being converted\r
279      * @return {Float} The comparison value\r
280      */\r
281     asFloat : function(s) {\r
282         var val = parseFloat(String(s).replace(/,/g, ""));\r
283         return isNaN(val) ? 0 : val;\r
284     },\r
285     \r
286     /**\r
287      * Integer sorting\r
288      * @param {Mixed} s The value being converted\r
289      * @return {Number} The comparison value\r
290      */\r
291     asInt : function(s) {\r
292         var val = parseInt(String(s).replace(/,/g, ""), 10);\r
293         return isNaN(val) ? 0 : val;\r
294     }\r
295 };/**
296  * @class Ext.data.Record
297  * <p>Instances of this class encapsulate both Record <em>definition</em> information, and Record
298  * <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
299  * to access Records cached in an {@link Ext.data.Store} object.</p>
300  * <p>Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
301  * Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
302  * objects.</p>
303  * <p>Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
304  * In order to copy data from one Store to another, use the {@link #copy} method to create an exact
305  * copy of the Record, and insert the new instance into the other Store.</p>
306  * <p>When serializing a Record for submission to the server, be aware that it contains many private
307  * properties, and also a reference to its owning Store which in turn holds references to its Records.
308  * This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
309  * <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
310  * <p>Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.</p>
311  * @constructor
312  * This constructor should not be used to create Record objects. Instead, use {@link #create} to
313  * generate a subclass of Ext.data.Record configured with information about its constituent fields.
314  * @param {Object} data (Optional) An object, the properties of which provide values for the new Record's
315  * fields. If not specified the <code>{@link Ext.data.Field#defaultValue defaultValue}</code>
316  * for each field will be assigned.
317  * @param {Object} id (Optional) The id of the Record. This id should be unique, and is used by the
318  * {@link Ext.data.Store} object which owns the Record to index its collection of Records. If
319  * an <code>id</code> is not specified a <b><code>{@link #phantom}</code></b> Record will be created
320  * with an {@link #Record.id automatically generated id}.
321  */
322 Ext.data.Record = function(data, id){
323     // if no id, call the auto id method
324     this.id = (id || id === 0) ? id : Ext.data.Record.id(this);
325     this.data = data || {};
326 };
327
328 /**
329  * Generate a constructor for a specific Record layout.
330  * @param {Array} o An Array of <b>{@link Ext.data.Field Field}</b> definition objects.
331  * The constructor generated by this method may be used to create new Record instances. The data
332  * object must contain properties named after the {@link Ext.data.Field field}
333  * <b><tt>{@link Ext.data.Field#name}s</tt></b>.  Example usage:<pre><code>
334 // create a Record constructor from a description of the fields
335 var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
336     {{@link Ext.data.Field#name name}: 'title', {@link Ext.data.Field#mapping mapping}: 'topic_title'},
337     {name: 'author', mapping: 'username', allowBlank: false},
338     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
339     {name: 'lastPost', mapping: 'post_time', type: 'date'},
340     {name: 'lastPoster', mapping: 'user2'},
341     {name: 'excerpt', mapping: 'post_text', allowBlank: false},
342     // In the simplest case, if no properties other than <tt>name</tt> are required,
343     // a field definition may consist of just a String for the field name.
344     'signature'
345 ]);
346
347 // create Record instance
348 var myNewRecord = new TopicRecord(
349     {
350         title: 'Do my job please',
351         author: 'noobie',
352         totalPosts: 1,
353         lastPost: new Date(),
354         lastPoster: 'Animal',
355         excerpt: 'No way dude!',
356         signature: ''
357     },
358     id // optionally specify the id of the record otherwise {@link #Record.id one is auto-assigned}
359 );
360 myStore.{@link Ext.data.Store#add add}(myNewRecord);
361 </code></pre>
362  * @method create
363  * @return {function} A constructor which is used to create new Records according
364  * to the definition. The constructor has the same signature as {@link #Ext.data.Record}.
365  * @static
366  */
367 Ext.data.Record.create = function(o){
368     var f = Ext.extend(Ext.data.Record, {});
369     var p = f.prototype;
370     p.fields = new Ext.util.MixedCollection(false, function(field){
371         return field.name;
372     });
373     for(var i = 0, len = o.length; i < len; i++){
374         p.fields.add(new Ext.data.Field(o[i]));
375     }
376     f.getField = function(name){
377         return p.fields.get(name);
378     };
379     return f;
380 };
381
382 Ext.data.Record.PREFIX = 'ext-record';
383 Ext.data.Record.AUTO_ID = 1;
384 Ext.data.Record.EDIT = 'edit';
385 Ext.data.Record.REJECT = 'reject';
386 Ext.data.Record.COMMIT = 'commit';
387
388
389 /**
390  * Generates a sequential id. This method is typically called when a record is {@link #create}d
391  * and {@link #Record no id has been specified}. The returned id takes the form:
392  * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
393  * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.PREFIX</tt>
394  * (defaults to <tt>'ext-record'</tt>)</p></li>
395  * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.AUTO_ID</tt>
396  * (defaults to <tt>1</tt> initially)</p></li>
397  * </ul></div>
398  * @param {Record} rec The record being created.  The record does not exist, it's a {@link #phantom}.
399  * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
400  */
401 Ext.data.Record.id = function(rec) {
402     rec.phantom = true;
403     return [Ext.data.Record.PREFIX, '-', Ext.data.Record.AUTO_ID++].join('');
404 };
405
406 Ext.data.Record.prototype = {
407     /**
408      * <p><b>This property is stored in the Record definition's <u>prototype</u></b></p>
409      * A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record.  Read-only.
410      * @property fields
411      * @type Ext.util.MixedCollection
412      */
413     /**
414      * An object hash representing the data for this Record. Every field name in the Record definition
415      * is represented by a property of that name in this object. Note that unless you specified a field
416      * with {@link Ext.data.Field#name name} "id" in the Record definition, this will <b>not</b> contain
417      * an <tt>id</tt> property.
418      * @property data
419      * @type {Object}
420      */
421     /**
422      * The unique ID of the Record {@link #Record as specified at construction time}.
423      * @property id
424      * @type {Object}
425      */
426     /**
427      * Readonly flag - true if this Record has been modified.
428      * @type Boolean
429      */
430     dirty : false,
431     editing : false,
432     error: null,
433     /**
434      * This object contains a key and value storing the original values of all modified
435      * fields or is null if no fields have been modified.
436      * @property modified
437      * @type {Object}
438      */
439     modified: null,
440     /**
441      * <tt>false</tt> when the record does not yet exist in a server-side database (see
442      * {@link #markDirty}).  Any record which has a real database pk set as its id property
443      * is NOT a phantom -- it's real.
444      * @property phantom
445      * @type {Boolean}
446      */
447     phantom : false,
448
449     // private
450     join : function(store){
451         /**
452          * The {@link Ext.data.Store} to which this Record belongs.
453          * @property store
454          * @type {Ext.data.Store}
455          */
456         this.store = store;
457     },
458
459     /**
460      * Set the {@link Ext.data.Field#name named field} to the specified value.  For example:
461      * <pre><code>
462 // record has a field named 'firstname'
463 var Employee = Ext.data.Record.{@link #create}([
464     {name: 'firstname'},
465     ...
466 ]);
467
468 // update the 2nd record in the store:
469 var rec = myStore.{@link Ext.data.Store#getAt getAt}(1);
470
471 // set the value (shows dirty flag):
472 rec.set('firstname', 'Betty');
473
474 // commit the change (removes dirty flag):
475 rec.{@link #commit}();
476
477 // update the record in the store, bypass setting dirty flag,
478 // and do not store the change in the {@link Ext.data.Store#getModifiedRecords modified records}
479 rec.{@link #data}['firstname'] = 'Wilma'); // updates record, but not the view
480 rec.{@link #commit}(); // updates the view
481      * </code></pre>
482      * <b>Notes</b>:<div class="mdetail-params"><ul>
483      * <li>If the store has a writer and <code>autoSave=true</code>, each set()
484      * will execute an XHR to the server.</li>
485      * <li>Use <code>{@link #beginEdit}</code> to prevent the store's <code>update</code>
486      * event firing while using set().</li>
487      * <li>Use <code>{@link #endEdit}</code> to have the store's <code>update</code>
488      * event fire.</li>
489      * </ul></div>
490      * @param {String} name The {@link Ext.data.Field#name name of the field} to set.
491      * @param {Object} value The value to set the field to.
492      */
493     set : function(name, value){
494         var isObj = (typeof value === 'object');
495         if(!isObj && String(this.data[name]) === String(value)){
496             return;
497         } else if (isObj && Ext.encode(this.data[name]) === Ext.encode(value)) {
498             return;
499         }
500         this.dirty = true;
501         if(!this.modified){
502             this.modified = {};
503         }
504         if(typeof this.modified[name] == 'undefined'){
505             this.modified[name] = this.data[name];
506         }
507         this.data[name] = value;
508         if(!this.editing){
509             this.afterEdit();
510         }
511     },
512
513     // private
514     afterEdit: function(){
515         if(this.store){
516             this.store.afterEdit(this);
517         }
518     },
519
520     // private
521     afterReject: function(){
522         if(this.store){
523             this.store.afterReject(this);
524         }
525     },
526
527     // private
528     afterCommit: function(){
529         if(this.store){
530             this.store.afterCommit(this);
531         }
532     },
533
534     /**
535      * Get the value of the {@link Ext.data.Field#name named field}.
536      * @param {String} name The {@link Ext.data.Field#name name of the field} to get the value of.
537      * @return {Object} The value of the field.
538      */
539     get : function(name){
540         return this.data[name];
541     },
542
543     /**
544      * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
545      * are relayed to the containing store.
546      * See also: <code>{@link #endEdit}</code> and <code>{@link #cancelEdit}</code>.
547      */
548     beginEdit : function(){
549         this.editing = true;
550         this.modified = this.modified || {};
551     },
552
553     /**
554      * Cancels all changes made in the current edit operation.
555      */
556     cancelEdit : function(){
557         this.editing = false;
558         delete this.modified;
559     },
560
561     /**
562      * End an edit. If any data was modified, the containing store is notified
563      * (ie, the store's <code>update</code> event will fire).
564      */
565     endEdit : function(){
566         this.editing = false;
567         if(this.dirty){
568             this.afterEdit();
569         }
570     },
571
572     /**
573      * Usually called by the {@link Ext.data.Store} which owns the Record.
574      * Rejects all changes made to the Record since either creation, or the last commit operation.
575      * Modified fields are reverted to their original values.
576      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
577      * to have their code notified of reject operations.</p>
578      * @param {Boolean} silent (optional) True to skip notification of the owning
579      * store of the change (defaults to false)
580      */
581     reject : function(silent){
582         var m = this.modified;
583         for(var n in m){
584             if(typeof m[n] != "function"){
585                 this.data[n] = m[n];
586             }
587         }
588         this.dirty = false;
589         delete this.modified;
590         this.editing = false;
591         if(silent !== true){
592             this.afterReject();
593         }
594     },
595
596     /**
597      * Usually called by the {@link Ext.data.Store} which owns the Record.
598      * Commits all changes made to the Record since either creation, or the last commit operation.
599      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
600      * to have their code notified of commit operations.</p>
601      * @param {Boolean} silent (optional) True to skip notification of the owning
602      * store of the change (defaults to false)
603      */
604     commit : function(silent){
605         this.dirty = false;
606         delete this.modified;
607         this.editing = false;
608         if(silent !== true){
609             this.afterCommit();
610         }
611     },
612
613     /**
614      * Gets a hash of only the fields that have been modified since this Record was created or commited.
615      * @return Object
616      */
617     getChanges : function(){
618         var m = this.modified, cs = {};
619         for(var n in m){
620             if(m.hasOwnProperty(n)){
621                 cs[n] = this.data[n];
622             }
623         }
624         return cs;
625     },
626
627     // private
628     hasError : function(){
629         return this.error !== null;
630     },
631
632     // private
633     clearError : function(){
634         this.error = null;
635     },
636
637     /**
638      * Creates a copy of this Record.
639      * @param {String} id (optional) A new Record id, defaults to {@link #Record.id autogenerating an id}.
640      * Note: if an <code>id</code> is not specified the copy created will be a
641      * <code>{@link #phantom}</code> Record.
642      * @return {Record}
643      */
644     copy : function(newId) {
645         return new this.constructor(Ext.apply({}, this.data), newId || this.id);
646     },
647
648     /**
649      * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
650      * since the load or last commit.
651      * @param {String} fieldName {@link Ext.data.Field.{@link Ext.data.Field#name}
652      * @return {Boolean}
653      */
654     isModified : function(fieldName){
655         return !!(this.modified && this.modified.hasOwnProperty(fieldName));
656     },
657
658     /**
659      * By default returns <tt>false</tt> if any {@link Ext.data.Field field} within the
660      * record configured with <tt>{@link Ext.data.Field#allowBlank} = false</tt> returns
661      * <tt>true</tt> from an {@link Ext}.{@link Ext#isEmpty isempty} test.
662      * @return {Boolean}
663      */
664     isValid : function() {
665         return this.fields.find(function(f) {
666             return (f.allowBlank === false && Ext.isEmpty(this.data[f.name])) ? true : false;
667         },this) ? false : true;
668     },
669
670     /**
671      * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>.  This method
672      * is used interally when adding <code>{@link #phantom}</code> records to a
673      * {@link Ext.data.Store#writer writer enabled store}.</p>
674      * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
675      * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
676      * have a create action composed for it during {@link Ext.data.Store#save store save}
677      * operations.</p>
678      */
679     markDirty : function(){
680         this.dirty = true;
681         if(!this.modified){
682             this.modified = {};
683         }
684         this.fields.each(function(f) {
685             this.modified[f.name] = this.data[f.name];
686         },this);
687     }
688 };/**
689  * @class Ext.StoreMgr
690  * @extends Ext.util.MixedCollection
691  * The default global group of stores.
692  * @singleton
693  */
694 Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
695     /**
696      * @cfg {Object} listeners @hide
697      */
698
699     /**
700      * Registers one or more Stores with the StoreMgr. You do not normally need to register stores
701      * manually.  Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered. 
702      * @param {Ext.data.Store} store1 A Store instance
703      * @param {Ext.data.Store} store2 (optional)
704      * @param {Ext.data.Store} etc... (optional)
705      */
706     register : function(){
707         for(var i = 0, s; (s = arguments[i]); i++){
708             this.add(s);
709         }
710     },
711
712     /**
713      * Unregisters one or more Stores with the StoreMgr
714      * @param {String/Object} id1 The id of the Store, or a Store instance
715      * @param {String/Object} id2 (optional)
716      * @param {String/Object} etc... (optional)
717      */
718     unregister : function(){
719         for(var i = 0, s; (s = arguments[i]); i++){
720             this.remove(this.lookup(s));
721         }
722     },
723
724     /**
725      * Gets a registered Store by id
726      * @param {String/Object} id The id of the Store, or a Store instance
727      * @return {Ext.data.Store}
728      */
729     lookup : function(id){
730         if(Ext.isArray(id)){
731             var fields = ['field1'], expand = !Ext.isArray(id[0]);
732             if(!expand){
733                 for(var i = 2, len = id[0].length; i <= len; ++i){
734                     fields.push('field' + i);
735                 }
736             }
737             return new Ext.data.ArrayStore({
738                 fields: fields,
739                 data: id,
740                 expandData: expand,
741                 autoDestroy: true,
742                 autoCreated: true
743
744             });
745         }
746         return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
747     },
748
749     // getKey implementation for MixedCollection
750     getKey : function(o){
751          return o.storeId;
752     }
753 });/**
754  * @class Ext.data.Store
755  * @extends Ext.util.Observable
756  * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
757  * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
758  * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
759  * <p><u>Retrieving Data</u></p>
760  * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
761  * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
762  * <li>{@link #data} to automatically pass in data</li>
763  * <li>{@link #loadData} to manually pass in data</li>
764  * </ul></div></p>
765  * <p><u>Reading Data</u></p>
766  * <p>A Store object has no inherent knowledge of the format of the data object (it could be
767  * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
768  * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
769  * object.</p>
770  * <p><u>Store Types</u></p>
771  * <p>There are several implementations of Store available which are customized for use with
772  * a specific DataReader implementation.  Here is an example using an ArrayStore which implicitly
773  * creates a reader commensurate to an Array data object.</p>
774  * <pre><code>
775 var myStore = new Ext.data.ArrayStore({
776     fields: ['fullname', 'first'],
777     idIndex: 0 // id for each record will be the first element
778 });
779  * </code></pre>
780  * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
781  * <pre><code>
782 // create a {@link Ext.data.Record Record} constructor:
783 var rt = Ext.data.Record.create([
784     {name: 'fullname'},
785     {name: 'first'}
786 ]);
787 var myStore = new Ext.data.Store({
788     // explicitly create reader
789     reader: new Ext.data.ArrayReader(
790         {
791             idIndex: 0  // id for each record will be the first element
792         },
793         rt // recordType
794     )
795 });
796  * </code></pre>
797  * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
798  * <pre><code>
799 var myData = [
800     [1, 'Fred Flintstone', 'Fred'],  // note that id for the record is the first element
801     [2, 'Barney Rubble', 'Barney']
802 ];
803 myStore.loadData(myData);
804  * </code></pre>
805  * <p>Records are cached and made available through accessor functions.  An example of adding
806  * a record to the store:</p>
807  * <pre><code>
808 var defaultData = {
809     fullname: 'Full Name',
810     first: 'First Name'
811 };
812 var recId = 100; // provide unique id for the record
813 var r = new myStore.recordType(defaultData, ++recId); // create new record
814 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
815  * </code></pre>
816  * @constructor
817  * Creates a new Store.
818  * @param {Object} config A config object containing the objects needed for the Store to access data,
819  * and read the data into Records.
820  * @xtype store
821  */
822 Ext.data.Store = function(config){
823     this.data = new Ext.util.MixedCollection(false);
824     this.data.getKey = function(o){
825         return o.id;
826     };
827     /**
828      * See the <code>{@link #baseParams corresponding configuration option}</code>
829      * for a description of this property.
830      * To modify this property see <code>{@link #setBaseParam}</code>.
831      * @property
832      */
833     this.baseParams = {};
834
835     // temporary removed-records cache
836     this.removed = [];
837
838     if(config && config.data){
839         this.inlineData = config.data;
840         delete config.data;
841     }
842
843     Ext.apply(this, config);
844     
845     this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
846
847     if(this.url && !this.proxy){
848         this.proxy = new Ext.data.HttpProxy({url: this.url});
849     }
850     // If Store is RESTful, so too is the DataProxy
851     if (this.restful === true && this.proxy) {
852         // When operating RESTfully, a unique transaction is generated for each record.
853         this.batch = false;
854         Ext.data.Api.restify(this.proxy);
855     }
856
857     if(this.reader){ // reader passed
858         if(!this.recordType){
859             this.recordType = this.reader.recordType;
860         }
861         if(this.reader.onMetaChange){
862             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
863         }
864         if (this.writer) { // writer passed
865             this.writer.meta = this.reader.meta;
866             this.pruneModifiedRecords = true;
867         }
868     }
869
870     /**
871      * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
872      * {@link Ext.data.DataReader Reader}. Read-only.
873      * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
874      * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
875      * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
876      * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
877 // create the data store
878 var store = new Ext.data.ArrayStore({
879     autoDestroy: true,
880     fields: [
881        {name: 'company'},
882        {name: 'price', type: 'float'},
883        {name: 'change', type: 'float'},
884        {name: 'pctChange', type: 'float'},
885        {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
886     ]
887 });
888 store.loadData(myData);
889
890 // create the Grid
891 var grid = new Ext.grid.EditorGridPanel({
892     store: store,
893     colModel: new Ext.grid.ColumnModel({
894         columns: [
895             {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
896             {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
897             {header: 'Change', renderer: change, dataIndex: 'change'},
898             {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
899             {header: 'Last Updated', width: 85,
900                 renderer: Ext.util.Format.dateRenderer('m/d/Y'),
901                 dataIndex: 'lastChange'}
902         ],
903         defaults: {
904             sortable: true,
905             width: 75
906         }
907     }),
908     autoExpandColumn: 'company', // match the id specified in the column model
909     height:350,
910     width:600,
911     title:'Array Grid',
912     tbar: [{
913         text: 'Add Record',
914         handler : function(){
915             var defaultData = {
916                 change: 0,
917                 company: 'New Company',
918                 lastChange: (new Date()).clearTime(),
919                 pctChange: 0,
920                 price: 10
921             };
922             var recId = 3; // provide unique id
923             var p = new store.recordType(defaultData, recId); // create new record
924             grid.stopEditing();
925             store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
926             grid.startEditing(0, 0);
927         }
928     }]
929 });
930      * </code></pre>
931      * @property recordType
932      * @type Function
933      */
934
935     if(this.recordType){
936         /**
937          * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
938          * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
939          * @property fields
940          * @type Ext.util.MixedCollection
941          */
942         this.fields = this.recordType.prototype.fields;
943     }
944     this.modified = [];
945
946     this.addEvents(
947         /**
948          * @event datachanged
949          * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
950          * widget that is using this Store as a Record cache should refresh its view.
951          * @param {Store} this
952          */
953         'datachanged',
954         /**
955          * @event metachange
956          * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
957          * @param {Store} this
958          * @param {Object} meta The JSON metadata
959          */
960         'metachange',
961         /**
962          * @event add
963          * Fires when Records have been {@link #add}ed to the Store
964          * @param {Store} this
965          * @param {Ext.data.Record[]} records The array of Records added
966          * @param {Number} index The index at which the record(s) were added
967          */
968         'add',
969         /**
970          * @event remove
971          * Fires when a Record has been {@link #remove}d from the Store
972          * @param {Store} this
973          * @param {Ext.data.Record} record The Record that was removed
974          * @param {Number} index The index at which the record was removed
975          */
976         'remove',
977         /**
978          * @event update
979          * Fires when a Record has been updated
980          * @param {Store} this
981          * @param {Ext.data.Record} record The Record that was updated
982          * @param {String} operation The update operation being performed.  Value may be one of:
983          * <pre><code>
984  Ext.data.Record.EDIT
985  Ext.data.Record.REJECT
986  Ext.data.Record.COMMIT
987          * </code></pre>
988          */
989         'update',
990         /**
991          * @event clear
992          * Fires when the data cache has been cleared.
993          * @param {Store} this
994          */
995         'clear',
996         /**
997          * @event exception
998          * <p>Fires if an exception occurs in the Proxy during a remote request.
999          * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1000          * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1001          * for additional details.
1002          * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1003          * for description.
1004          */
1005         'exception',
1006         /**
1007          * @event beforeload
1008          * Fires before a request is made for a new data object.  If the beforeload handler returns
1009          * <tt>false</tt> the {@link #load} action will be canceled.
1010          * @param {Store} this
1011          * @param {Object} options The loading options that were specified (see {@link #load} for details)
1012          */
1013         'beforeload',
1014         /**
1015          * @event load
1016          * Fires after a new set of Records has been loaded.
1017          * @param {Store} this
1018          * @param {Ext.data.Record[]} records The Records that were loaded
1019          * @param {Object} options The loading options that were specified (see {@link #load} for details)
1020          */
1021         'load',
1022         /**
1023          * @event loadexception
1024          * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
1025          * event instead.</p>
1026          * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1027          * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1028          * for additional details.
1029          * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1030          * for description.
1031          */
1032         'loadexception',
1033         /**
1034          * @event beforewrite
1035          * @param {DataProxy} this
1036          * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1037          * @param {Record/Array[Record]} rs
1038          * @param {Object} options The loading options that were specified. Edit <code>options.params</code> to add Http parameters to the request.  (see {@link #save} for details)
1039          * @param {Object} arg The callback's arg object passed to the {@link #request} function
1040          */
1041         'beforewrite',
1042         /**
1043          * @event write
1044          * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
1045          * Success or failure of the action is available in the <code>result['successProperty']</code> property.
1046          * The server-code might set the <code>successProperty</code> to <tt>false</tt> if a database validation
1047          * failed, for example.
1048          * @param {Ext.data.Store} store
1049          * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1050          * @param {Object} result The 'data' picked-out out of the response for convenience.
1051          * @param {Ext.Direct.Transaction} res
1052          * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
1053          */
1054         'write'
1055     );
1056
1057     if(this.proxy){
1058         this.relayEvents(this.proxy,  ['loadexception', 'exception']);
1059     }
1060     // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
1061     if (this.writer) {
1062         this.on({
1063             scope: this,
1064             add: this.createRecords,
1065             remove: this.destroyRecord,
1066             update: this.updateRecord
1067         });
1068     }
1069
1070     this.sortToggle = {};
1071     if(this.sortField){
1072         this.setDefaultSort(this.sortField, this.sortDir);
1073     }else if(this.sortInfo){
1074         this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
1075     }
1076
1077     Ext.data.Store.superclass.constructor.call(this);
1078
1079     if(this.id){
1080         this.storeId = this.id;
1081         delete this.id;
1082     }
1083     if(this.storeId){
1084         Ext.StoreMgr.register(this);
1085     }
1086     if(this.inlineData){
1087         this.loadData(this.inlineData);
1088         delete this.inlineData;
1089     }else if(this.autoLoad){
1090         this.load.defer(10, this, [
1091             typeof this.autoLoad == 'object' ?
1092                 this.autoLoad : undefined]);
1093     }
1094 };
1095 Ext.extend(Ext.data.Store, Ext.util.Observable, {
1096     /**
1097      * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
1098      * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
1099      * assignment.</p>
1100      */
1101     /**
1102      * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
1103      * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
1104      * Typically this option, or the <code>{@link #data}</code> option will be specified.
1105      */
1106     /**
1107      * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
1108      * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
1109      * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
1110      * be passed to the store's {@link #load} method.
1111      */
1112     /**
1113      * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
1114      * access to a data object.  See <code>{@link #url}</code>.
1115      */
1116     /**
1117      * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
1118      * Typically this option, or the <code>{@link #url}</code> option will be specified.
1119      */
1120     /**
1121      * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
1122      * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
1123      * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
1124      */
1125     /**
1126      * @cfg {Ext.data.DataWriter} writer
1127      * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
1128      * to the server-side database.</p>
1129      * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
1130      * events on the store are monitored in order to remotely {@link #createRecords create records},
1131      * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
1132      * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
1133      * <br><p>Sample implementation:
1134      * <pre><code>
1135 var writer = new {@link Ext.data.JsonWriter}({
1136     encode: true,
1137     writeAllFields: true // write all fields, not just those that changed
1138 });
1139
1140 // Typical Store collecting the Proxy, Reader and Writer together.
1141 var store = new Ext.data.Store({
1142     storeId: 'user',
1143     root: 'records',
1144     proxy: proxy,
1145     reader: reader,
1146     writer: writer,     // <-- plug a DataWriter into the store just as you would a Reader
1147     paramsAsHash: true,
1148     autoSave: false    // <-- false to delay executing create, update, destroy requests
1149                         //     until specifically told to do so.
1150 });
1151      * </code></pre></p>
1152      */
1153     writer : undefined,
1154     /**
1155      * @cfg {Object} baseParams
1156      * <p>An object containing properties which are to be sent as parameters
1157      * for <i>every</i> HTTP request.</p>
1158      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
1159      * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
1160      * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
1161      * for more details.</p>
1162      * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
1163      * method.
1164      * @property
1165      */
1166     /**
1167      * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
1168      * {@link #load} operation.  Note that for local sorting, the <tt>direction</tt> property is
1169      * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
1170      * For example:<pre><code>
1171 sortInfo: {
1172     field: 'fieldName',
1173     direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
1174 }
1175 </code></pre>
1176      */
1177     /**
1178      * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
1179      * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
1180      * in place (defaults to <tt>false</tt>).
1181      * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
1182      * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
1183      * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
1184      * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
1185      * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
1186      * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
1187      * </ul></div></p>
1188      */
1189     remoteSort : false,
1190
1191     /**
1192      * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
1193      * to is destroyed (defaults to <tt>false</tt>).
1194      * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
1195      */
1196     autoDestroy : false,
1197
1198     /**
1199      * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
1200      * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
1201      * for the accessor method to retrieve the modified records.
1202      */
1203     pruneModifiedRecords : false,
1204
1205     /**
1206      * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
1207      * for the details of what this may contain. This may be useful for accessing any params which were used
1208      * to load the current Record cache.
1209      * @property
1210      */
1211     lastOptions : null,
1212
1213     /**
1214      * @cfg {Boolean} autoSave
1215      * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
1216      * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
1217      * to send all modifiedRecords to the server.</p>
1218      * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
1219      */
1220     autoSave : true,
1221
1222     /**
1223      * @cfg {Boolean} batch
1224      * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
1225      * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
1226      * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
1227      * to <tt>false</tt>.</p>
1228      * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
1229      * generated for each record.</p>
1230      */
1231     batch : true,
1232
1233     /**
1234      * @cfg {Boolean} restful
1235      * Defaults to <tt>false</tt>.  Set to <tt>true</tt> to have the Store and the set
1236      * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
1237      * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
1238      * action is described in {@link Ext.data.Api#restActions}.  For additional information
1239      * see {@link Ext.data.DataProxy#restful}.
1240      * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
1241      * internally be set to <tt>false</tt>.</p>
1242      */
1243     restful: false,
1244     
1245     /**
1246      * @cfg {Object} paramNames
1247      * <p>An object containing properties which specify the names of the paging and
1248      * sorting parameters passed to remote servers when loading blocks of data. By default, this
1249      * object takes the following form:</p><pre><code>
1250 {
1251     start : 'start',  // The parameter name which specifies the start row
1252     limit : 'limit',  // The parameter name which specifies number of rows to return
1253     sort : 'sort',    // The parameter name which specifies the column to sort on
1254     dir : 'dir'       // The parameter name which specifies the sort direction
1255 }
1256 </code></pre>
1257      * <p>The server must produce the requested data block upon receipt of these parameter names.
1258      * If different parameter names are required, this property can be overriden using a configuration
1259      * property.</p>
1260      * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
1261      * the parameter names to use in its {@link #load requests}.
1262      */
1263     paramNames : undefined,
1264     
1265     /**
1266      * @cfg {Object} defaultParamNames
1267      * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
1268      * for all stores, this object should be changed on the store prototype.
1269      */
1270     defaultParamNames : {
1271         start : 'start',
1272         limit : 'limit',
1273         sort : 'sort',
1274         dir : 'dir'
1275     },
1276
1277     /**
1278      * Destroys the store.
1279      */
1280     destroy : function(){
1281         if(this.storeId){
1282             Ext.StoreMgr.unregister(this);
1283         }
1284         this.data = null;
1285         Ext.destroy(this.proxy);
1286         this.reader = this.writer = null;
1287         this.purgeListeners();
1288     },
1289
1290     /**
1291      * Add Records to the Store and fires the {@link #add} event.  To add Records
1292      * to the store from a remote source use <code>{@link #load}({add:true})</code>.
1293      * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
1294      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
1295      * to add to the cache. See {@link #recordType}.
1296      */
1297     add : function(records){
1298         records = [].concat(records);
1299         if(records.length < 1){
1300             return;
1301         }
1302         for(var i = 0, len = records.length; i < len; i++){
1303             records[i].join(this);
1304         }
1305         var index = this.data.length;
1306         this.data.addAll(records);
1307         if(this.snapshot){
1308             this.snapshot.addAll(records);
1309         }
1310         this.fireEvent('add', this, records, index);
1311     },
1312
1313     /**
1314      * (Local sort only) Inserts the passed Record into the Store at the index where it
1315      * should go based on the current sort information.
1316      * @param {Ext.data.Record} record
1317      */
1318     addSorted : function(record){
1319         var index = this.findInsertIndex(record);
1320         this.insert(index, record);
1321     },
1322
1323     /**
1324      * Remove a Record from the Store and fires the {@link #remove} event.
1325      * @param {Ext.data.Record} record The Ext.data.Record object to remove from the cache.
1326      */
1327     remove : function(record){
1328         var index = this.data.indexOf(record);
1329         if(index > -1){
1330             this.data.removeAt(index);
1331             if(this.pruneModifiedRecords){
1332                 this.modified.remove(record);
1333             }
1334             if(this.snapshot){
1335                 this.snapshot.remove(record);
1336             }
1337             this.fireEvent('remove', this, record, index);
1338         }
1339     },
1340
1341     /**
1342      * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
1343      * @param {Number} index The index of the record to remove.
1344      */
1345     removeAt : function(index){
1346         this.remove(this.getAt(index));
1347     },
1348
1349     /**
1350      * Remove all Records from the Store and fires the {@link #clear} event.
1351      */
1352     removeAll : function(){
1353         this.data.clear();
1354         if(this.snapshot){
1355             this.snapshot.clear();
1356         }
1357         if(this.pruneModifiedRecords){
1358             this.modified = [];
1359         }
1360         this.fireEvent('clear', this);
1361     },
1362
1363     /**
1364      * Inserts Records into the Store at the given index and fires the {@link #add} event.
1365      * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
1366      * @param {Number} index The start index at which to insert the passed Records.
1367      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
1368      */
1369     insert : function(index, records){
1370         records = [].concat(records);
1371         for(var i = 0, len = records.length; i < len; i++){
1372             this.data.insert(index, records[i]);
1373             records[i].join(this);
1374         }
1375         this.fireEvent('add', this, records, index);
1376     },
1377
1378     /**
1379      * Get the index within the cache of the passed Record.
1380      * @param {Ext.data.Record} record The Ext.data.Record object to find.
1381      * @return {Number} The index of the passed Record. Returns -1 if not found.
1382      */
1383     indexOf : function(record){
1384         return this.data.indexOf(record);
1385     },
1386
1387     /**
1388      * Get the index within the cache of the Record with the passed id.
1389      * @param {String} id The id of the Record to find.
1390      * @return {Number} The index of the Record. Returns -1 if not found.
1391      */
1392     indexOfId : function(id){
1393         return this.data.indexOfKey(id);
1394     },
1395
1396     /**
1397      * Get the Record with the specified id.
1398      * @param {String} id The id of the Record to find.
1399      * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
1400      */
1401     getById : function(id){
1402         return this.data.key(id);
1403     },
1404
1405     /**
1406      * Get the Record at the specified index.
1407      * @param {Number} index The index of the Record to find.
1408      * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
1409      */
1410     getAt : function(index){
1411         return this.data.itemAt(index);
1412     },
1413
1414     /**
1415      * Returns a range of Records between specified indices.
1416      * @param {Number} startIndex (optional) The starting index (defaults to 0)
1417      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
1418      * @return {Ext.data.Record[]} An array of Records
1419      */
1420     getRange : function(start, end){
1421         return this.data.getRange(start, end);
1422     },
1423
1424     // private
1425     storeOptions : function(o){
1426         o = Ext.apply({}, o);
1427         delete o.callback;
1428         delete o.scope;
1429         this.lastOptions = o;
1430     },
1431
1432     /**
1433      * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
1434      * <br><p>Notes:</p><div class="mdetail-params"><ul>
1435      * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
1436      * loaded. To perform any post-processing where information from the load call is required, specify
1437      * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
1438      * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
1439      * properties in the <code>options.params</code> property to establish the initial position within the
1440      * dataset, and the number of Records to cache on each read from the Proxy.</li>
1441      * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
1442      * will be automatically included with the posted parameters according to the specified
1443      * <code>{@link #paramNames}</code>.</li>
1444      * </ul></div>
1445      * @param {Object} options An object containing properties which control loading options:<ul>
1446      * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
1447      * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
1448      * <code>{@link #baseParams}</code> of the same name.</p>
1449      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
1450      * <li><b><tt>callback</tt></b> : Function<div class="sub-desc"><p>A function to be called after the Records
1451      * have been loaded. The <tt>callback</tt> is called after the load event and is passed the following arguments:<ul>
1452      * <li><tt>r</tt> : Ext.data.Record[]</li>
1453      * <li><tt>options</tt>: Options object from the load call</li>
1454      * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div></li>
1455      * <li><b><tt>scope</tt></b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
1456      * to the Store object)</p></div></li>
1457      * <li><b><tt>add</tt></b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
1458      * replace the current cache.  <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
1459      * </ul>
1460      * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
1461      * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
1462      */
1463     load : function(options) {
1464         options = options || {};
1465         this.storeOptions(options);
1466         if(this.sortInfo && this.remoteSort){
1467             var pn = this.paramNames;
1468             options.params = options.params || {};
1469             options.params[pn.sort] = this.sortInfo.field;
1470             options.params[pn.dir] = this.sortInfo.direction;
1471         }
1472         try {
1473             return this.execute('read', null, options); // <-- null represents rs.  No rs for load actions.
1474         } catch(e) {
1475             this.handleException(e);
1476             return false;
1477         }
1478     },
1479
1480     /**
1481      * updateRecord  Should not be used directly.  This method will be called automatically if a Writer is set.
1482      * Listens to 'update' event.
1483      * @param {Object} store
1484      * @param {Object} record
1485      * @param {Object} action
1486      * @private
1487      */
1488     updateRecord : function(store, record, action) {
1489         if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid))) {
1490             this.save();
1491         }
1492     },
1493
1494     /**
1495      * Should not be used directly.  Store#add will call this automatically if a Writer is set
1496      * @param {Object} store
1497      * @param {Object} rs
1498      * @param {Object} index
1499      * @private
1500      */
1501     createRecords : function(store, rs, index) {
1502         for (var i = 0, len = rs.length; i < len; i++) {
1503             if (rs[i].phantom && rs[i].isValid()) {
1504                 rs[i].markDirty();  // <-- Mark new records dirty
1505                 this.modified.push(rs[i]);  // <-- add to modified
1506             }
1507         }
1508         if (this.autoSave === true) {
1509             this.save();
1510         }
1511     },
1512
1513     /**
1514      * Destroys a record or records.  Should not be used directly.  It's called by Store#remove if a Writer is set.
1515      * @param {Store} this
1516      * @param {Ext.data.Record/Ext.data.Record[]}
1517      * @param {Number} index
1518      * @private
1519      */
1520     destroyRecord : function(store, record, index) {
1521         if (this.modified.indexOf(record) != -1) {  // <-- handled already if @cfg pruneModifiedRecords == true
1522             this.modified.remove(record);
1523         }
1524         if (!record.phantom) {
1525             this.removed.push(record);
1526
1527             // since the record has already been removed from the store but the server request has not yet been executed,
1528             // must keep track of the last known index this record existed.  If a server error occurs, the record can be
1529             // put back into the store.  @see Store#createCallback where the record is returned when response status === false
1530             record.lastIndex = index;
1531
1532             if (this.autoSave === true) {
1533                 this.save();
1534             }
1535         }
1536     },
1537
1538     /**
1539      * This method should generally not be used directly.  This method is called internally
1540      * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
1541      * {@link #remove}, or {@link #update} events fire.
1542      * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
1543      * @param {Record/Record[]} rs
1544      * @param {Object} options
1545      * @throws Error
1546      * @private
1547      */
1548     execute : function(action, rs, options) {
1549         // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
1550         if (!Ext.data.Api.isAction(action)) {
1551             throw new Ext.data.Api.Error('execute', action);
1552         }
1553         // make sure options has a params key
1554         options = Ext.applyIf(options||{}, {
1555             params: {}
1556         });
1557
1558         // have to separate before-events since load has a different signature than create,destroy and save events since load does not
1559         // include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
1560         var doRequest = true;
1561
1562         if (action === 'read') {
1563             doRequest = this.fireEvent('beforeload', this, options);
1564         }
1565         else {
1566             // if Writer is configured as listful, force single-recoord rs to be [{}} instead of {}
1567             if (this.writer.listful === true && this.restful !== true) {
1568                 rs = (Ext.isArray(rs)) ? rs : [rs];
1569             }
1570             // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
1571             else if (Ext.isArray(rs) && rs.length == 1) {
1572                 rs = rs.shift();
1573             }
1574             // Write the action to options.params
1575             if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
1576                 this.writer.write(action, options.params, rs);
1577             }
1578         }
1579         if (doRequest !== false) {
1580             // Send request to proxy.
1581             var params = Ext.apply({}, options.params, this.baseParams);
1582             if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
1583                 params.xaction = action;
1584             }
1585             // Note:  Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.  We'll flip it now
1586             // and send the value into DataProxy#request, since it's the value which maps to the DataProxy#api
1587             this.proxy.request(Ext.data.Api.actions[action], rs, params, this.reader, this.createCallback(action, rs), this, options);
1588         }
1589         return doRequest;
1590     },
1591
1592     /**
1593      * Saves all pending changes to the store.  If the commensurate Ext.data.Api.actions action is not configured, then
1594      * the configured <code>{@link #url}</code> will be used.
1595      * <pre>
1596      * change            url
1597      * ---------------   --------------------
1598      * removed records   Ext.data.Api.actions.destroy
1599      * phantom records   Ext.data.Api.actions.create
1600      * {@link #getModifiedRecords modified records}  Ext.data.Api.actions.update
1601      * </pre>
1602      * @TODO:  Create extensions of Error class and send associated Record with thrown exceptions.
1603      * e.g.:  Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
1604      */
1605     save : function() {
1606         if (!this.writer) {
1607             throw new Ext.data.Store.Error('writer-undefined');
1608         }
1609
1610         // DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
1611         if (this.removed.length) {
1612             this.doTransaction('destroy', this.removed);
1613         }
1614
1615         // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
1616         var rs = [].concat(this.getModifiedRecords());
1617         if (!rs.length) { // Bail-out if empty...
1618             return true;
1619         }
1620
1621         // CREATE:  Next check for phantoms within rs.  splice-off and execute create.
1622         var phantoms = [];
1623         for (var i = rs.length-1; i >= 0; i--) {
1624             if (rs[i].phantom === true) {
1625                 var rec = rs.splice(i, 1).shift();
1626                 if (rec.isValid()) {
1627                     phantoms.push(rec);
1628                 }
1629             } else if (!rs[i].isValid()) { // <-- while we're here, splice-off any !isValid real records
1630                 rs.splice(i,1);
1631             }
1632         }
1633         // If we have valid phantoms, create them...
1634         if (phantoms.length) {
1635             this.doTransaction('create', phantoms);
1636         }
1637
1638         // UPDATE:  And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
1639         if (rs.length) {
1640             this.doTransaction('update', rs);
1641         }
1642         return true;
1643     },
1644
1645     // private.  Simply wraps call to Store#execute in try/catch.  Defers to Store#handleException on error.  Loops if batch: false
1646     doTransaction : function(action, rs) {
1647         function transaction(records) {
1648             try {
1649                 this.execute(action, records);
1650             } catch (e) {
1651                 this.handleException(e);
1652             }
1653         }
1654         if (this.batch === false) {
1655             for (var i = 0, len = rs.length; i < len; i++) {
1656                 transaction.call(this, rs[i]);
1657             }
1658         } else {
1659             transaction.call(this, rs);
1660         }
1661     },
1662
1663     // @private callback-handler for remote CRUD actions
1664     // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1665     createCallback : function(action, rs) {
1666         var actions = Ext.data.Api.actions;
1667         return (action == 'read') ? this.loadRecords : function(data, response, success) {
1668             // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1669             this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, data);
1670             // If success === false here, exception will have been called in DataProxy
1671             if (success === true) {
1672                 this.fireEvent('write', this, action, data, response, rs);
1673             }
1674         };
1675     },
1676
1677     // Clears records from modified array after an exception event.
1678     // NOTE:  records are left marked dirty.  Do we want to commit them even though they were not updated/realized?
1679     clearModified : function(rs) {
1680         if (Ext.isArray(rs)) {
1681             for (var n=rs.length-1;n>=0;n--) {
1682                 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1683             }
1684         } else {
1685             this.modified.splice(this.modified.indexOf(rs), 1);
1686         }
1687     },
1688
1689     // remap record ids in MixedCollection after records have been realized.  @see Store#onCreateRecords, @see DataReader#realize
1690     reMap : function(record) {
1691         if (Ext.isArray(record)) {
1692             for (var i = 0, len = record.length; i < len; i++) {
1693                 this.reMap(record[i]);
1694             }
1695         } else {
1696             delete this.data.map[record._phid];
1697             this.data.map[record.id] = record;
1698             var index = this.data.keys.indexOf(record._phid);
1699             this.data.keys.splice(index, 1, record.id);
1700             delete record._phid;
1701         }
1702     },
1703
1704     // @protected onCreateRecord proxy callback for create action
1705     onCreateRecords : function(success, rs, data) {
1706         if (success === true) {
1707             try {
1708                 this.reader.realize(rs, data);
1709                 this.reMap(rs);
1710             }
1711             catch (e) {
1712                 this.handleException(e);
1713                 if (Ext.isArray(rs)) {
1714                     // Recurse to run back into the try {}.  DataReader#realize splices-off the rs until empty.
1715                     this.onCreateRecords(success, rs, data);
1716                 }
1717             }
1718         }
1719     },
1720
1721     // @protected, onUpdateRecords proxy callback for update action
1722     onUpdateRecords : function(success, rs, data) {
1723         if (success === true) {
1724             try {
1725                 this.reader.update(rs, data);
1726             } catch (e) {
1727                 this.handleException(e);
1728                 if (Ext.isArray(rs)) {
1729                     // Recurse to run back into the try {}.  DataReader#update splices-off the rs until empty.
1730                     this.onUpdateRecords(success, rs, data);
1731                 }
1732             }
1733         }
1734     },
1735
1736     // @protected onDestroyRecords proxy callback for destroy action
1737     onDestroyRecords : function(success, rs, data) {
1738         // splice each rec out of this.removed
1739         rs = (rs instanceof Ext.data.Record) ? [rs] : rs;
1740         for (var i=0,len=rs.length;i<len;i++) {
1741             this.removed.splice(this.removed.indexOf(rs[i]), 1);
1742         }
1743         if (success === false) {
1744             // put records back into store if remote destroy fails.
1745             // @TODO: Might want to let developer decide.
1746             for (i=rs.length-1;i>=0;i--) {
1747                 this.insert(rs[i].lastIndex, rs[i]);    // <-- lastIndex set in Store#destroyRecord
1748             }
1749         }
1750     },
1751
1752     // protected handleException.  Possibly temporary until Ext framework has an exception-handler.
1753     handleException : function(e) {
1754         // @see core/Error.js
1755         Ext.handleError(e);
1756     },
1757
1758     /**
1759      * <p>Reloads the Record cache from the configured Proxy using the configured {@link Ext.data.Reader Reader} and
1760      * the options from the last load operation performed.</p>
1761      * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1762      * @param {Object} options (optional) An <tt>Object</tt> containing {@link #load loading options} which may
1763      * override the options used in the last {@link #load} operation. See {@link #load} for details (defaults to
1764      * <tt>null</tt>, in which case the {@link #lastOptions} are used).
1765      */
1766     reload : function(options){
1767         this.load(Ext.applyIf(options||{}, this.lastOptions));
1768     },
1769
1770     // private
1771     // Called as a callback by the Reader during a load operation.
1772     loadRecords : function(o, options, success){
1773         if(!o || success === false){
1774             if(success !== false){
1775                 this.fireEvent('load', this, [], options);
1776             }
1777             if(options.callback){
1778                 options.callback.call(options.scope || this, [], options, false, o);
1779             }
1780             return;
1781         }
1782         var r = o.records, t = o.totalRecords || r.length;
1783         if(!options || options.add !== true){
1784             if(this.pruneModifiedRecords){
1785                 this.modified = [];
1786             }
1787             for(var i = 0, len = r.length; i < len; i++){
1788                 r[i].join(this);
1789             }
1790             if(this.snapshot){
1791                 this.data = this.snapshot;
1792                 delete this.snapshot;
1793             }
1794             this.data.clear();
1795             this.data.addAll(r);
1796             this.totalLength = t;
1797             this.applySort();
1798             this.fireEvent('datachanged', this);
1799         }else{
1800             this.totalLength = Math.max(t, this.data.length+r.length);
1801             this.add(r);
1802         }
1803         this.fireEvent('load', this, r, options);
1804         if(options.callback){
1805             options.callback.call(options.scope || this, r, options, true);
1806         }
1807     },
1808
1809     /**
1810      * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1811      * which understands the format of the data must have been configured in the constructor.
1812      * @param {Object} data The data block from which to read the Records.  The format of the data expected
1813      * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1814      * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1815      * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1816      * the existing cache.
1817      * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1818      * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1819      * new, unique ids will be added.
1820      */
1821     loadData : function(o, append){
1822         var r = this.reader.readRecords(o);
1823         this.loadRecords(r, {add: append}, true);
1824     },
1825
1826     /**
1827      * Gets the number of cached records.
1828      * <p>If using paging, this may not be the total size of the dataset. If the data object
1829      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1830      * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
1831      * @return {Number} The number of Records in the Store's cache.
1832      */
1833     getCount : function(){
1834         return this.data.length || 0;
1835     },
1836
1837     /**
1838      * Gets the total number of records in the dataset as returned by the server.
1839      * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1840      * must contain the dataset size. For remote data sources, the value for this property
1841      * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1842      * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1843      * <b>Note</b>: see the Important note in {@link #load}.</p>
1844      * @return {Number} The number of Records as specified in the data object passed to the Reader
1845      * by the Proxy.
1846      * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1847      */
1848     getTotalCount : function(){
1849         return this.totalLength || 0;
1850     },
1851
1852     /**
1853      * Returns an object describing the current sort state of this Store.
1854      * @return {Object} The sort state of the Store. An object with two properties:<ul>
1855      * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1856      * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1857      * </ul>
1858      * See <tt>{@link #sortInfo}</tt> for additional details.
1859      */
1860     getSortState : function(){
1861         return this.sortInfo;
1862     },
1863
1864     // private
1865     applySort : function(){
1866         if(this.sortInfo && !this.remoteSort){
1867             var s = this.sortInfo, f = s.field;
1868             this.sortData(f, s.direction);
1869         }
1870     },
1871
1872     // private
1873     sortData : function(f, direction){
1874         direction = direction || 'ASC';
1875         var st = this.fields.get(f).sortType;
1876         var fn = function(r1, r2){
1877             var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
1878             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
1879         };
1880         this.data.sort(direction, fn);
1881         if(this.snapshot && this.snapshot != this.data){
1882             this.snapshot.sort(direction, fn);
1883         }
1884     },
1885
1886     /**
1887      * Sets the default sort column and order to be used by the next {@link #load} operation.
1888      * @param {String} fieldName The name of the field to sort by.
1889      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1890      */
1891     setDefaultSort : function(field, dir){
1892         dir = dir ? dir.toUpperCase() : 'ASC';
1893         this.sortInfo = {field: field, direction: dir};
1894         this.sortToggle[field] = dir;
1895     },
1896
1897     /**
1898      * Sort the Records.
1899      * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1900      * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1901      * @param {String} fieldName The name of the field to sort by.
1902      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1903      */
1904     sort : function(fieldName, dir){
1905         var f = this.fields.get(fieldName);
1906         if(!f){
1907             return false;
1908         }
1909         if(!dir){
1910             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
1911                 dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
1912             }else{
1913                 dir = f.sortDir;
1914             }
1915         }
1916         var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
1917         var si = (this.sortInfo) ? this.sortInfo : null;
1918
1919         this.sortToggle[f.name] = dir;
1920         this.sortInfo = {field: f.name, direction: dir};
1921         if(!this.remoteSort){
1922             this.applySort();
1923             this.fireEvent('datachanged', this);
1924         }else{
1925             if (!this.load(this.lastOptions)) {
1926                 if (st) {
1927                     this.sortToggle[f.name] = st;
1928                 }
1929                 if (si) {
1930                     this.sortInfo = si;
1931                 }
1932             }
1933         }
1934     },
1935
1936     /**
1937      * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1938      * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1939      * Returning <tt>false</tt> aborts and exits the iteration.
1940      * @param {Object} scope (optional) The scope in which to call the function (defaults to the {@link Ext.data.Record Record}).
1941      */
1942     each : function(fn, scope){
1943         this.data.each(fn, scope);
1944     },
1945
1946     /**
1947      * Gets all {@link Ext.data.Record records} modified since the last commit.  Modified records are
1948      * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1949      * included.  See also <tt>{@link #pruneModifiedRecords}</tt> and
1950      * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1951      * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1952      * modifications.  To obtain modified fields within a modified record see
1953      *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1954      */
1955     getModifiedRecords : function(){
1956         return this.modified;
1957     },
1958
1959     // private
1960     createFilterFn : function(property, value, anyMatch, caseSensitive){
1961         if(Ext.isEmpty(value, false)){
1962             return false;
1963         }
1964         value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
1965         return function(r){
1966             return value.test(r.data[property]);
1967         };
1968     },
1969
1970     /**
1971      * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1972      * and <tt>end</tt> and returns the result.
1973      * @param {String} property A field in each record
1974      * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1975      * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1976      * @return {Number} The sum
1977      */
1978     sum : function(property, start, end){
1979         var rs = this.data.items, v = 0;
1980         start = start || 0;
1981         end = (end || end === 0) ? end : rs.length-1;
1982
1983         for(var i = start; i <= end; i++){
1984             v += (rs[i].data[property] || 0);
1985         }
1986         return v;
1987     },
1988
1989     /**
1990      * Filter the {@link Ext.data.Record records} by a specified property.
1991      * @param {String} field A field on your records
1992      * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1993      * against the field.
1994      * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1995      * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1996      */
1997     filter : function(property, value, anyMatch, caseSensitive){
1998         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1999         return fn ? this.filterBy(fn) : this.clearFilter();
2000     },
2001
2002     /**
2003      * Filter by a function. The specified function will be called for each
2004      * Record in this Store. If the function returns <tt>true</tt> the Record is included,
2005      * otherwise it is filtered out.
2006      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2007      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2008      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2009      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2010      * </ul>
2011      * @param {Object} scope (optional) The scope of the function (defaults to this)
2012      */
2013     filterBy : function(fn, scope){
2014         this.snapshot = this.snapshot || this.data;
2015         this.data = this.queryBy(fn, scope||this);
2016         this.fireEvent('datachanged', this);
2017     },
2018
2019     /**
2020      * Query the records by a specified property.
2021      * @param {String} field A field on your records
2022      * @param {String/RegExp} value Either a string that the field
2023      * should begin with, or a RegExp to test against the field.
2024      * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
2025      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2026      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2027      */
2028     query : function(property, value, anyMatch, caseSensitive){
2029         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2030         return fn ? this.queryBy(fn) : this.data.clone();
2031     },
2032
2033     /**
2034      * Query the cached records in this Store using a filtering function. The specified function
2035      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
2036      * included in the results.
2037      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2038      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2039      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2040      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2041      * </ul>
2042      * @param {Object} scope (optional) The scope of the function (defaults to this)
2043      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2044      **/
2045     queryBy : function(fn, scope){
2046         var data = this.snapshot || this.data;
2047         return data.filterBy(fn, scope||this);
2048     },
2049
2050     /**
2051      * Finds the index of the first matching record in this store by a specific property/value.
2052      * @param {String} property A property on your objects
2053      * @param {String/RegExp} value Either a string that the property value
2054      * should begin with, or a RegExp to test against the property.
2055      * @param {Number} startIndex (optional) The index to start searching at
2056      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
2057      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2058      * @return {Number} The matched index or -1
2059      */
2060     find : function(property, value, start, anyMatch, caseSensitive){
2061         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2062         return fn ? this.data.findIndexBy(fn, null, start) : -1;
2063     },
2064
2065     /**
2066      * Finds the index of the first matching record in this store by a specific property/value.
2067      * @param {String} property A property on your objects
2068      * @param {String/RegExp} value The value to match against
2069      * @param {Number} startIndex (optional) The index to start searching at
2070      * @return {Number} The matched index or -1
2071      */
2072     findExact: function(property, value, start){
2073         return this.data.findIndexBy(function(rec){
2074             return rec.get(property) === value;
2075         }, this, start);
2076     },
2077
2078     /**
2079      * Find the index of the first matching Record in this Store by a function.
2080      * If the function returns <tt>true</tt> it is considered a match.
2081      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2082      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2083      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2084      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2085      * </ul>
2086      * @param {Object} scope (optional) The scope of the function (defaults to this)
2087      * @param {Number} startIndex (optional) The index to start searching at
2088      * @return {Number} The matched index or -1
2089      */
2090     findBy : function(fn, scope, start){
2091         return this.data.findIndexBy(fn, scope, start);
2092     },
2093
2094     /**
2095      * Collects unique values for a particular dataIndex from this store.
2096      * @param {String} dataIndex The property to collect
2097      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
2098      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
2099      * @return {Array} An array of the unique values
2100      **/
2101     collect : function(dataIndex, allowNull, bypassFilter){
2102         var d = (bypassFilter === true && this.snapshot) ?
2103                 this.snapshot.items : this.data.items;
2104         var v, sv, r = [], l = {};
2105         for(var i = 0, len = d.length; i < len; i++){
2106             v = d[i].data[dataIndex];
2107             sv = String(v);
2108             if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
2109                 l[sv] = true;
2110                 r[r.length] = v;
2111             }
2112         }
2113         return r;
2114     },
2115
2116     /**
2117      * Revert to a view of the Record cache with no filtering applied.
2118      * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
2119      * {@link #datachanged} event.
2120      */
2121     clearFilter : function(suppressEvent){
2122         if(this.isFiltered()){
2123             this.data = this.snapshot;
2124             delete this.snapshot;
2125             if(suppressEvent !== true){
2126                 this.fireEvent('datachanged', this);
2127             }
2128         }
2129     },
2130
2131     /**
2132      * Returns true if this store is currently filtered
2133      * @return {Boolean}
2134      */
2135     isFiltered : function(){
2136         return this.snapshot && this.snapshot != this.data;
2137     },
2138
2139     // private
2140     afterEdit : function(record){
2141         if(this.modified.indexOf(record) == -1){
2142             this.modified.push(record);
2143         }
2144         this.fireEvent('update', this, record, Ext.data.Record.EDIT);
2145     },
2146
2147     // private
2148     afterReject : function(record){
2149         this.modified.remove(record);
2150         this.fireEvent('update', this, record, Ext.data.Record.REJECT);
2151     },
2152
2153     // private
2154     afterCommit : function(record){
2155         this.modified.remove(record);
2156         this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
2157     },
2158
2159     /**
2160      * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
2161      * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
2162      * Ext.data.Record.COMMIT.
2163      */
2164     commitChanges : function(){
2165         var m = this.modified.slice(0);
2166         this.modified = [];
2167         for(var i = 0, len = m.length; i < len; i++){
2168             m[i].commit();
2169         }
2170     },
2171
2172     /**
2173      * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
2174      */
2175     rejectChanges : function(){
2176         var m = this.modified.slice(0);
2177         this.modified = [];
2178         for(var i = 0, len = m.length; i < len; i++){
2179             m[i].reject();
2180         }
2181     },
2182
2183     // private
2184     onMetaChange : function(meta, rtype, o){
2185         this.recordType = rtype;
2186         this.fields = rtype.prototype.fields;
2187         delete this.snapshot;
2188         if(meta.sortInfo){
2189             this.sortInfo = meta.sortInfo;
2190         }else if(this.sortInfo  && !this.fields.get(this.sortInfo.field)){
2191             delete this.sortInfo;
2192         }
2193         this.modified = [];
2194         this.fireEvent('metachange', this, this.reader.meta);
2195     },
2196
2197     // private
2198     findInsertIndex : function(record){
2199         this.suspendEvents();
2200         var data = this.data.clone();
2201         this.data.add(record);
2202         this.applySort();
2203         var index = this.data.indexOf(record);
2204         this.data = data;
2205         this.resumeEvents();
2206         return index;
2207     },
2208
2209     /**
2210      * Set the value for a property name in this store's {@link #baseParams}.  Usage:</p><pre><code>
2211 myStore.setBaseParam('foo', {bar:3});
2212 </code></pre>
2213      * @param {String} name Name of the property to assign
2214      * @param {Mixed} value Value to assign the <tt>name</tt>d property
2215      **/
2216     setBaseParam : function (name, value){
2217         this.baseParams = this.baseParams || {};
2218         this.baseParams[name] = value;
2219     }
2220 });
2221
2222 Ext.reg('store', Ext.data.Store);
2223
2224 /**
2225  * @class Ext.data.Store.Error
2226  * @extends Ext.Error
2227  * Store Error extension.
2228  * @param {String} name
2229  */
2230 Ext.data.Store.Error = Ext.extend(Ext.Error, {
2231     name: 'Ext.data.Store'
2232 });
2233 Ext.apply(Ext.data.Store.Error.prototype, {
2234     lang: {
2235         'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
2236     }
2237 });
2238
2239 /**
2240  * @class Ext.data.Field
2241  * <p>This class encapsulates the field definition information specified in the field definition objects
2242  * passed to {@link Ext.data.Record#create}.</p>
2243  * <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
2244  * and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
2245  */
2246 Ext.data.Field = function(config){
2247     if(typeof config == "string"){
2248         config = {name: config};
2249     }
2250     Ext.apply(this, config);
2251
2252     if(!this.type){
2253         this.type = "auto";
2254     }
2255
2256     var st = Ext.data.SortTypes;
2257     // named sortTypes are supported, here we look them up
2258     if(typeof this.sortType == "string"){
2259         this.sortType = st[this.sortType];
2260     }
2261
2262     // set default sortType for strings and dates
2263     if(!this.sortType){
2264         switch(this.type){
2265             case "string":
2266                 this.sortType = st.asUCString;
2267                 break;
2268             case "date":
2269                 this.sortType = st.asDate;
2270                 break;
2271             default:
2272                 this.sortType = st.none;
2273         }
2274     }
2275
2276     // define once
2277     var stripRe = /[\$,%]/g;
2278
2279     // prebuilt conversion function for this field, instead of
2280     // switching every time we're reading a value
2281     if(!this.convert){
2282         var cv, dateFormat = this.dateFormat;
2283         switch(this.type){
2284             case "":
2285             case "auto":
2286             case undefined:
2287                 cv = function(v){ return v; };
2288                 break;
2289             case "string":
2290                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
2291                 break;
2292             case "int":
2293                 cv = function(v){
2294                     return v !== undefined && v !== null && v !== '' ?
2295                            parseInt(String(v).replace(stripRe, ""), 10) : '';
2296                     };
2297                 break;
2298             case "float":
2299                 cv = function(v){
2300                     return v !== undefined && v !== null && v !== '' ?
2301                            parseFloat(String(v).replace(stripRe, ""), 10) : '';
2302                     };
2303                 break;
2304             case "bool":
2305             case "boolean":
2306                 cv = function(v){ return v === true || v === "true" || v == 1; };
2307                 break;
2308             case "date":
2309                 cv = function(v){
2310                     if(!v){
2311                         return '';
2312                     }
2313                     if(Ext.isDate(v)){
2314                         return v;
2315                     }
2316                     if(dateFormat){
2317                         if(dateFormat == "timestamp"){
2318                             return new Date(v*1000);
2319                         }
2320                         if(dateFormat == "time"){
2321                             return new Date(parseInt(v, 10));
2322                         }
2323                         return Date.parseDate(v, dateFormat);
2324                     }
2325                     var parsed = Date.parse(v);
2326                     return parsed ? new Date(parsed) : null;
2327                 };
2328              break;
2329
2330         }
2331         this.convert = cv;
2332     }
2333 };
2334
2335 Ext.data.Field.prototype = {
2336     /**
2337      * @cfg {String} name
2338      * The name by which the field is referenced within the Record. This is referenced by, for example,
2339      * the <tt>dataIndex</tt> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
2340      * <p>Note: In the simplest case, if no properties other than <tt>name</tt> are required, a field
2341      * definition may consist of just a String for the field name.</p>
2342      */
2343     /**
2344      * @cfg {String} type
2345      * (Optional) The data type for conversion to displayable value if <tt>{@link Ext.data.Field#convert convert}</tt>
2346      * has not been specified. Possible values are
2347      * <div class="mdetail-params"><ul>
2348      * <li>auto (Default, implies no conversion)</li>
2349      * <li>string</li>
2350      * <li>int</li>
2351      * <li>float</li>
2352      * <li>boolean</li>
2353      * <li>date</li></ul></div>
2354      */
2355     /**
2356      * @cfg {Function} convert
2357      * (Optional) A function which converts the value provided by the Reader into an object that will be stored
2358      * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
2359      * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
2360      * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
2361      * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
2362      * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
2363      *  ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
2364      * </ul></div>
2365      * <pre><code>
2366 // example of convert function
2367 function fullName(v, record){
2368     return record.name.last + ', ' + record.name.first;
2369 }
2370
2371 function location(v, record){
2372     return !record.city ? '' : (record.city + ', ' + record.state);
2373 }
2374
2375 var Dude = Ext.data.Record.create([
2376     {name: 'fullname',  convert: fullName},
2377     {name: 'firstname', mapping: 'name.first'},
2378     {name: 'lastname',  mapping: 'name.last'},
2379     {name: 'city', defaultValue: 'homeless'},
2380     'state',
2381     {name: 'location',  convert: location}
2382 ]);
2383
2384 // create the data store
2385 var store = new Ext.data.Store({
2386     reader: new Ext.data.JsonReader(
2387         {
2388             idProperty: 'key',
2389             root: 'daRoot',  
2390             totalProperty: 'total'
2391         },
2392         Dude  // recordType
2393     )
2394 });
2395
2396 var myData = [
2397     { key: 1,
2398       name: { first: 'Fat',    last:  'Albert' }
2399       // notice no city, state provided in data object
2400     },
2401     { key: 2,
2402       name: { first: 'Barney', last:  'Rubble' },
2403       city: 'Bedrock', state: 'Stoneridge'
2404     },
2405     { key: 3,
2406       name: { first: 'Cliff',  last:  'Claven' },
2407       city: 'Boston',  state: 'MA'
2408     }
2409 ];
2410      * </code></pre>
2411      */
2412     /**
2413      * @cfg {String} dateFormat
2414      * (Optional) A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
2415      * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
2416      * javascript millisecond timestamp.
2417      */
2418     dateFormat: null,
2419     /**
2420      * @cfg {Mixed} defaultValue
2421      * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
2422      * when the item referenced by the <tt>{@link Ext.data.Field#mapping mapping}</tt> does not exist in the data
2423      * object (i.e. undefined). (defaults to "")
2424      */
2425     defaultValue: "",
2426     /**
2427      * @cfg {String/Number} mapping
2428      * <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
2429      * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
2430      * If the path expression is the same as the field name, the mapping may be omitted.</p>
2431      * <p>The form of the mapping expression depends on the Reader being used.</p>
2432      * <div class="mdetail-params"><ul>
2433      * <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
2434      * expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li>
2435      * <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
2436      * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
2437      * <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
2438      * of the field's value. Defaults to the field specification's Array position.</div></li>
2439      * </ul></div>
2440      * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
2441      * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
2442      * return the desired data.</p>
2443      */
2444     mapping: null,
2445     /**
2446      * @cfg {Function} sortType
2447      * (Optional) A function which converts a Field's value to a comparable value in order to ensure
2448      * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
2449      * sort example:<pre><code>
2450 // current sort     after sort we want
2451 // +-+------+          +-+------+
2452 // |1|First |          |1|First |
2453 // |2|Last  |          |3|Second|
2454 // |3|Second|          |2|Last  |
2455 // +-+------+          +-+------+
2456
2457 sortType: function(value) {
2458    switch (value.toLowerCase()) // native toLowerCase():
2459    {
2460       case 'first': return 1;
2461       case 'second': return 2;
2462       default: return 3;
2463    }
2464 }
2465      * </code></pre>
2466      */
2467     sortType : null,
2468     /**
2469      * @cfg {String} sortDir
2470      * (Optional) Initial direction to sort (<tt>"ASC"</tt> or  <tt>"DESC"</tt>).  Defaults to
2471      * <tt>"ASC"</tt>.
2472      */
2473     sortDir : "ASC",
2474         /**
2475          * @cfg {Boolean} allowBlank 
2476          * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <tt>true</tt>.
2477          * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
2478          * to evaluate to <tt>false</tt>.
2479          */
2480         allowBlank : true
2481 };/**\r
2482  * @class Ext.data.DataReader\r
2483  * Abstract base class for reading structured data from a data source and converting\r
2484  * it into an object containing {@link Ext.data.Record} objects and metadata for use\r
2485  * by an {@link Ext.data.Store}.  This class is intended to be extended and should not\r
2486  * be created directly. For existing implementations, see {@link Ext.data.ArrayReader},\r
2487  * {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.\r
2488  * @constructor Create a new DataReader\r
2489  * @param {Object} meta Metadata configuration options (implementation-specific).\r
2490  * @param {Array/Object} recordType\r
2491  * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which\r
2492  * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}\r
2493  * constructor created using {@link Ext.data.Record#create}.</p>\r
2494  */\r
2495 Ext.data.DataReader = function(meta, recordType){\r
2496     /**\r
2497      * This DataReader's configured metadata as passed to the constructor.\r
2498      * @type Mixed\r
2499      * @property meta\r
2500      */\r
2501     this.meta = meta;\r
2502     /**\r
2503      * @cfg {Array/Object} fields\r
2504      * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which\r
2505      * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}\r
2506      * constructor created from {@link Ext.data.Record#create}.</p>\r
2507      */\r
2508     this.recordType = Ext.isArray(recordType) ?\r
2509         Ext.data.Record.create(recordType) : recordType;\r
2510 };\r
2511 \r
2512 Ext.data.DataReader.prototype = {\r
2513 \r
2514     /**\r
2515      * Abstract method, overridden in {@link Ext.data.JsonReader}\r
2516      */\r
2517     buildExtractors : Ext.emptyFn,\r
2518 \r
2519     /**\r
2520      * Used for un-phantoming a record after a successful database insert.  Sets the records pk along with new data from server.\r
2521      * You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration.  The incoming\r
2522      * data from server will be merged with the data in the local record.\r
2523      * In addition, you <b>must</b> return record-data from the server in the same order received.\r
2524      * Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be suppressed.\r
2525      * @param {Record/Record[]} record The phantom record to be realized.\r
2526      * @param {Object/Object[]} data The new record data to apply.  Must include the primary-key from database defined in idProperty field.\r
2527      */\r
2528     realize: function(rs, data){\r
2529         if (Ext.isArray(rs)) {\r
2530             for (var i = rs.length - 1; i >= 0; i--) {\r
2531                 // recurse\r
2532                 if (Ext.isArray(data)) {\r
2533                     this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());\r
2534                 }\r
2535                 else {\r
2536                     // weird...rs is an array but data isn't??  recurse but just send in the whole invalid data object.\r
2537                     // the else clause below will detect !this.isData and throw exception.\r
2538                     this.realize(rs.splice(i,1).shift(), data);\r
2539                 }\r
2540             }\r
2541         }\r
2542         else {\r
2543             // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.\r
2544             if (Ext.isArray(data) && data.length == 1) {\r
2545                 data = data.shift();\r
2546             }\r
2547             if (!this.isData(data)) {\r
2548                 // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.\r
2549                 //rs.commit();\r
2550                 throw new Ext.data.DataReader.Error('realize', rs);\r
2551             }\r
2552             this.buildExtractors();\r
2553             var values = this.extractValues(data, rs.fields.items, rs.fields.items.length);\r
2554             rs.phantom = false; // <-- That's what it's all about\r
2555             rs._phid = rs.id;  // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords\r
2556             rs.id = data[this.meta.idProperty];\r
2557             rs.data = values;\r
2558             rs.commit();\r
2559         }\r
2560     },\r
2561 \r
2562     /**\r
2563      * Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.\r
2564      * You <b>must</b> return a complete new record from the server.  If you don't, your local record's missing fields\r
2565      * will be populated with the default values specified in your Ext.data.Record.create specification.  Without a defaultValue,\r
2566      * local fields will be populated with empty string "".  So return your entire record's data after both remote create and update.\r
2567      * In addition, you <b>must</b> return record-data from the server in the same order received.\r
2568      * Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be suppressed as the record receives\r
2569      * a fresh new data-hash.\r
2570      * @param {Record/Record[]} rs\r
2571      * @param {Object/Object[]} data\r
2572      */\r
2573     update : function(rs, data) {\r
2574         if (Ext.isArray(rs)) {\r
2575             for (var i=rs.length-1; i >= 0; i--) {\r
2576                 if (Ext.isArray(data)) {\r
2577                     this.update(rs.splice(i,1).shift(), data.splice(i,1).shift());\r
2578                 }\r
2579                 else {\r
2580                     // weird...rs is an array but data isn't??  recurse but just send in the whole data object.\r
2581                     // the else clause below will detect !this.isData and throw exception.\r
2582                     this.update(rs.splice(i,1).shift(), data);\r
2583                 }\r
2584             }\r
2585         }\r
2586         else {\r
2587                      // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.\r
2588             if (Ext.isArray(data) && data.length == 1) {\r
2589                 data = data.shift();\r
2590             }\r
2591             if (!this.isData(data)) {\r
2592                 // TODO: create custom Exception class to return record in thrown exception.  Allow exception-handler the choice\r
2593                 // to commit or not rather than blindly rs.commit() here.\r
2594                 rs.commit();\r
2595                 throw new Ext.data.DataReader.Error('update', rs);\r
2596             }\r
2597             this.buildExtractors();\r
2598             rs.data = this.extractValues(Ext.apply(rs.data, data), rs.fields.items, rs.fields.items.length);\r
2599             rs.commit();\r
2600         }\r
2601     },\r
2602 \r
2603     /**\r
2604      * Returns true if the supplied data-hash <b>looks</b> and quacks like data.  Checks to see if it has a key\r
2605      * corresponding to idProperty defined in your DataReader config containing non-empty pk.\r
2606      * @param {Object} data\r
2607      * @return {Boolean}\r
2608      */\r
2609     isData : function(data) {\r
2610         return (data && Ext.isObject(data) && !Ext.isEmpty(data[this.meta.idProperty])) ? true : false;\r
2611     }\r
2612 };\r
2613 \r
2614 /**\r
2615  * @class Ext.data.DataReader.Error\r
2616  * @extends Ext.Error\r
2617  * General error class for Ext.data.DataReader\r
2618  */\r
2619 Ext.data.DataReader.Error = Ext.extend(Ext.Error, {\r
2620     constructor : function(message, arg) {\r
2621         this.arg = arg;\r
2622         Ext.Error.call(this, message);\r
2623     },\r
2624     name: 'Ext.data.DataReader'\r
2625 });\r
2626 Ext.apply(Ext.data.DataReader.Error.prototype, {\r
2627     lang : {\r
2628         'update': "#update received invalid data from server.  Please see docs for DataReader#update and review your DataReader configuration.",\r
2629         'realize': "#realize was called with invalid remote-data.  Please see the docs for DataReader#realize and review your DataReader configuration.",\r
2630         'invalid-response': "#readResponse received an invalid response from the server."\r
2631     }\r
2632 });\r
2633 \r
2634 \r
2635 /**
2636  * @class Ext.data.DataWriter
2637  * <p>Ext.data.DataWriter facilitates create, update, and destroy actions between
2638  * an Ext.data.Store and a server-side framework. A Writer enabled Store will
2639  * automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
2640  * <p>Ext.data.DataWriter is an abstract base class which is intended to be extended
2641  * and should not be created directly. For existing implementations, see
2642  * {@link Ext.data.JsonWriter}.</p>
2643  * <p>Creating a writer is simple:</p>
2644  * <pre><code>
2645 var writer = new Ext.data.JsonWriter();
2646  * </code></pre>
2647  * <p>The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
2648  * <pre><code>
2649 // Create a standard HttpProxy instance.
2650 var proxy = new Ext.data.HttpProxy({
2651     url: 'app.php/users'
2652 });
2653  * </code></pre>
2654  * <p>For finer grained control, the proxy may also be configured with an <code>api</code>:</p>
2655  * <pre><code>
2656 // Use the api specification
2657 var proxy = new Ext.data.HttpProxy({
2658     api: {
2659         read    : 'app.php/users/read',
2660         create  : 'app.php/users/create',
2661         update  : 'app.php/users/update',
2662         destroy : 'app.php/users/destroy'
2663     }
2664 });
2665  * </code></pre>
2666  * <p>Creating a Writer enabled store:</p>
2667  * <pre><code>
2668 var store = new Ext.data.Store({
2669     proxy: proxy,
2670     reader: reader,
2671     writer: writer
2672 });
2673  * </code></pre>
2674  * @constructor Create a new DataWriter
2675  * @param {Object} meta Metadata configuration options (implementation-specific)
2676  * @param {Object} recordType Either an Array of field definition objects as specified
2677  * in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
2678  * using {@link Ext.data.Record#create}.
2679  */
2680 Ext.data.DataWriter = function(config){
2681     /**
2682      * This DataWriter's configured metadata as passed to the constructor.
2683      * @type Mixed
2684      * @property meta
2685      */
2686     Ext.apply(this, config);
2687 };
2688
2689 Ext.data.DataWriter.prototype = {
2690
2691     /**
2692      * @cfg {Boolean} writeAllFields
2693      * <tt>false</tt> by default.  Set <tt>true</tt> to have DataWriter return ALL fields of a modified
2694      * record -- not just those that changed.
2695      * <tt>false</tt> to have DataWriter only request modified fields from a record.
2696      */
2697     writeAllFields : false,
2698     /**
2699      * @cfg {Boolean} listful
2700      * <tt>false</tt> by default.  Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
2701      * even when acting upon a single record.
2702      */
2703     listful : false,    // <-- listful is actually not used internally here in DataWriter.  @see Ext.data.Store#execute.
2704
2705     /**
2706      * Writes data in preparation for server-write action.  Simply proxies to DataWriter#update, DataWriter#create
2707      * DataWriter#destroy.
2708      * @param {String} action [CREATE|UPDATE|DESTROY]
2709      * @param {Object} params The params-hash to write-to
2710      * @param {Record/Record[]} rs The recordset write.
2711      */
2712     write : function(action, params, rs) {
2713         this.render(action, rs, params, this[action](rs));
2714     },
2715
2716     /**
2717      * abstract method meant to be overridden by all DataWriter extensions.  It's the extension's job to apply the "data" to the "params".
2718      * The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
2719      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
2720      * @param {Record[]} rs Store recordset
2721      * @param {Object} params Http params to be sent to server.
2722      * @param {Object} data object populated according to DataReader meta-data.
2723      */
2724     render : Ext.emptyFn,
2725
2726     /**
2727      * update
2728      * @param {Object} p Params-hash to apply result to.
2729      * @param {Record/Record[]} rs Record(s) to write
2730      * @private
2731      */
2732     update : function(rs) {
2733         var params = {};
2734         if (Ext.isArray(rs)) {
2735             var data = [],
2736                 ids = [];
2737             Ext.each(rs, function(val){
2738                 ids.push(val.id);
2739                 data.push(this.updateRecord(val));
2740             }, this);
2741             params[this.meta.idProperty] = ids;
2742             params[this.meta.root] = data;
2743         }
2744         else if (rs instanceof Ext.data.Record) {
2745             params[this.meta.idProperty] = rs.id;
2746             params[this.meta.root] = this.updateRecord(rs);
2747         }
2748         return params;
2749     },
2750
2751     /**
2752      * @cfg {Function} saveRecord Abstract method that should be implemented in all subclasses
2753      * (e.g.: {@link Ext.data.JsonWriter#saveRecord JsonWriter.saveRecord}
2754      */
2755     updateRecord : Ext.emptyFn,
2756
2757     /**
2758      * create
2759      * @param {Object} p Params-hash to apply result to.
2760      * @param {Record/Record[]} rs Record(s) to write
2761      * @private
2762      */
2763     create : function(rs) {
2764         var params = {};
2765         if (Ext.isArray(rs)) {
2766             var data = [];
2767             Ext.each(rs, function(val){
2768                 data.push(this.createRecord(val));
2769             }, this);
2770             params[this.meta.root] = data;
2771         }
2772         else if (rs instanceof Ext.data.Record) {
2773             params[this.meta.root] = this.createRecord(rs);
2774         }
2775         return params;
2776     },
2777
2778     /**
2779      * @cfg {Function} createRecord Abstract method that should be implemented in all subclasses
2780      * (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
2781      */
2782     createRecord : Ext.emptyFn,
2783
2784     /**
2785      * destroy
2786      * @param {Object} p Params-hash to apply result to.
2787      * @param {Record/Record[]} rs Record(s) to write
2788      * @private
2789      */
2790     destroy : function(rs) {
2791         var params = {};
2792         if (Ext.isArray(rs)) {
2793             var data = [],
2794                 ids = [];
2795             Ext.each(rs, function(val){
2796                 data.push(this.destroyRecord(val));
2797             }, this);
2798             params[this.meta.root] = data;
2799         } else if (rs instanceof Ext.data.Record) {
2800             params[this.meta.root] = this.destroyRecord(rs);
2801         }
2802         return params;
2803     },
2804
2805     /**
2806      * @cfg {Function} destroyRecord Abstract method that should be implemented in all subclasses
2807      * (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
2808      */
2809     destroyRecord : Ext.emptyFn,
2810
2811     /**
2812      * Converts a Record to a hash
2813      * @param {Record}
2814      * @private
2815      */
2816     toHash : function(rec) {
2817         var map = rec.fields.map,
2818             data = {},
2819             raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
2820             m;
2821         Ext.iterate(raw, function(prop, value){
2822             if((m = map[prop])){
2823                 data[m.mapping ? m.mapping : m.name] = value;
2824             }
2825         });
2826         data[this.meta.idProperty] = rec.id;
2827         return data;
2828     }
2829 };/**\r
2830  * @class Ext.data.DataProxy\r
2831  * @extends Ext.util.Observable\r
2832  * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.\r
2833  * This class is intended to be extended and should not be created directly. For existing implementations,\r
2834  * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and\r
2835  * {@link Ext.data.MemoryProxy}.</p>\r
2836  * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}\r
2837  * (of the appropriate type which knows how to parse the data object) to provide a block of\r
2838  * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>\r
2839  * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the\r
2840  * config object to an {@link Ext.data.Connection}.</p>\r
2841  * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the\r
2842  * <code>load</code> method (deprecated). See\r
2843  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or\r
2844  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>\r
2845  * <p><b><u>Example 1</u></b></p>\r
2846  * <pre><code>\r
2847 proxy: new Ext.data.ScriptTagProxy({\r
2848     {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'\r
2849 }),\r
2850  * </code></pre>\r
2851  * <p><b><u>Example 2</u></b></p>\r
2852  * <pre><code>\r
2853 proxy : new Ext.data.HttpProxy({\r
2854     {@link Ext.data.Connection#method method}: 'GET',\r
2855     {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,\r
2856     {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}\r
2857     {@link #api}: {\r
2858         // all actions except the following will use above url\r
2859         create  : 'local/new.php',\r
2860         update  : 'local/update.php'\r
2861     }\r
2862 }),\r
2863  * </code></pre>\r
2864  */\r
2865 Ext.data.DataProxy = function(conn){\r
2866     // make sure we have a config object here to support ux proxies.\r
2867     // All proxies should now send config into superclass constructor.\r
2868     conn = conn || {};\r
2869 \r
2870     // This line caused a bug when people use custom Connection object having its own request method.\r
2871     // http://extjs.com/forum/showthread.php?t=67194.  Have to set DataProxy config\r
2872     //Ext.applyIf(this, conn);\r
2873 \r
2874     this.api     = conn.api;\r
2875     this.url     = conn.url;\r
2876     this.restful = conn.restful;\r
2877     this.listeners = conn.listeners;\r
2878 \r
2879     // deprecated\r
2880     this.prettyUrls = conn.prettyUrls;\r
2881 \r
2882     /**\r
2883      * @cfg {Object} api\r
2884      * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".\r
2885      * Defaults to:<pre><code>\r
2886 api: {\r
2887     read    : undefined,\r
2888     create  : undefined,\r
2889     update  : undefined,\r
2890     destroy : undefined\r
2891 }\r
2892 </code></pre>\r
2893      * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request\r
2894      * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>\r
2895      * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API\r
2896      * property should be modified before the action is requested using the corresponding before\r
2897      * action event.  For example to modify the URL associated with the load action:\r
2898      * <pre><code>\r
2899 // modify the url for the action\r
2900 myStore.on({\r
2901     beforeload: {\r
2902         fn: function (store, options) {\r
2903             // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.\r
2904             store.proxy.setUrl('changed1.php');\r
2905 \r
2906             // set optional second parameter to true to make this URL change\r
2907             // permanent, applying this URL for all subsequent requests.\r
2908             store.proxy.setUrl('changed1.php', true);\r
2909 \r
2910             // manually set the <b>private</b> connection URL.\r
2911             // <b>Warning:</b>  Accessing the private URL property should be avoided.\r
2912             // Use the public method <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> instead, shown above.\r
2913             // It should be noted that changing the URL like this will affect\r
2914             // the URL for just this request.  Subsequent requests will use the\r
2915             // API or URL defined in your initial proxy configuration.\r
2916             store.proxy.conn.url = 'changed1.php';\r
2917 \r
2918             // proxy URL will be superseded by API (only if proxy created to use ajax):\r
2919             // It should be noted that proxy API changes are permanent and will\r
2920             // be used for all subsequent requests.\r
2921             store.proxy.api.load = 'changed2.php';\r
2922 \r
2923             // However, altering the proxy API should be done using the public\r
2924             // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt> instead.\r
2925             store.proxy.setApi('load', 'changed2.php');\r
2926 \r
2927             // Or set the entire API with a config-object.\r
2928             // When using the config-object option, you must redefine the <b>entire</b>\r
2929             // API -- not just a specific action of it.\r
2930             store.proxy.setApi({\r
2931                 read    : 'changed_read.php',\r
2932                 create  : 'changed_create.php',\r
2933                 update  : 'changed_update.php',\r
2934                 destroy : 'changed_destroy.php'\r
2935             });\r
2936         }\r
2937     }\r
2938 });\r
2939      * </code></pre>\r
2940      * </p>\r
2941      */\r
2942     // Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.\r
2943     try {\r
2944         Ext.data.Api.prepare(this);\r
2945     } catch (e) {\r
2946         if (e instanceof Ext.data.Api.Error) {\r
2947             e.toConsole();\r
2948         }\r
2949     }\r
2950 \r
2951     this.addEvents(\r
2952         /**\r
2953          * @event exception\r
2954          * <p>Fires if an exception occurs in the Proxy during a remote request.\r
2955          * This event is relayed through a corresponding\r
2956          * {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},\r
2957          * so any Store instance may observe this event.\r
2958          * This event can be fired for one of two reasons:</p>\r
2959          * <div class="mdetail-params"><ul>\r
2960          * <li>remote-request <b>failed</b> : <div class="sub-desc">\r
2961          * The server did not return status === 200.\r
2962          * </div></li>\r
2963          * <li>remote-request <b>succeeded</b> : <div class="sub-desc">\r
2964          * The remote-request succeeded but the reader could not read the response.\r
2965          * This means the server returned data, but the configured Reader threw an\r
2966          * error while reading the response.  In this case, this event will be\r
2967          * raised and the caught error will be passed along into this event.\r
2968          * </div></li>\r
2969          * </ul></div>\r
2970          * <br><p>This event fires with two different contexts based upon the 2nd\r
2971          * parameter <tt>type [remote|response]</tt>.  The first four parameters\r
2972          * are identical between the two contexts -- only the final two parameters\r
2973          * differ.</p>\r
2974          * @param {DataProxy} this The proxy that sent the request\r
2975          * @param {String} type\r
2976          * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>\r
2977          * <div class="mdetail-params"><ul>\r
2978          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
2979          * <p>An <b>invalid</b> response from the server was returned: either 404,\r
2980          * 500 or the response meta-data does not match that defined in the DataReader\r
2981          * (e.g.: root, idProperty, successProperty).</p>\r
2982          * </div></li>\r
2983          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
2984          * <p>A <b>valid</b> response was returned from the server having\r
2985          * successProperty === false.  This response might contain an error-message\r
2986          * sent from the server.  For example, the user may have failed\r
2987          * authentication/authorization or a database validation error occurred.</p>\r
2988          * </div></li>\r
2989          * </ul></div>\r
2990          * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.\r
2991          * @param {Object} options The options for the action that were specified in the {@link #request}.\r
2992          * @param {Object} response\r
2993          * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
2994          * <div class="mdetail-params"><ul>\r
2995          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
2996          * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>\r
2997          * </div></li>\r
2998          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
2999          * <p>The decoded response object sent from the server.</p>\r
3000          * </div></li>\r
3001          * </ul></div>\r
3002          * @param {Mixed} arg\r
3003          * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
3004          * <div class="mdetail-params"><ul>\r
3005          * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">\r
3006          * <p>The JavaScript Error object caught if the configured Reader could not read the data.\r
3007          * If the remote request returns success===false, this parameter will be null.</p>\r
3008          * </div></li>\r
3009          * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">\r
3010          * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action\r
3011          * (Ext.data.Api.actions.create|update|destroy).</p>\r
3012          * </div></li>\r
3013          * </ul></div>\r
3014          */\r
3015         'exception',\r
3016         /**\r
3017          * @event beforeload\r
3018          * Fires before a request to retrieve a data object.\r
3019          * @param {DataProxy} this The proxy for the request\r
3020          * @param {Object} params The params object passed to the {@link #request} function\r
3021          */\r
3022         'beforeload',\r
3023         /**\r
3024          * @event load\r
3025          * Fires before the load method's callback is called.\r
3026          * @param {DataProxy} this The proxy for the request\r
3027          * @param {Object} o The request transaction object\r
3028          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
3029          */\r
3030         'load',\r
3031         /**\r
3032          * @event loadexception\r
3033          * <p>This event is <b>deprecated</b>.  The signature of the loadexception event\r
3034          * varies depending on the proxy, use the catch-all {@link #exception} event instead.\r
3035          * This event will fire in addition to the {@link #exception} event.</p>\r
3036          * @param {misc} misc See {@link #exception}.\r
3037          * @deprecated\r
3038          */\r
3039         'loadexception',\r
3040         /**\r
3041          * @event beforewrite\r
3042          * Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy\r
3043          * @param {DataProxy} this The proxy for the request\r
3044          * @param {String} action [Ext.data.Api.actions.create|update|destroy]\r
3045          * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.\r
3046          * @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.\r
3047          */\r
3048         'beforewrite',\r
3049         /**\r
3050          * @event write\r
3051          * Fires before the request-callback is called\r
3052          * @param {DataProxy} this The proxy that sent the request\r
3053          * @param {String} action [Ext.data.Api.actions.create|upate|destroy]\r
3054          * @param {Object} data The data object extracted from the server-response\r
3055          * @param {Object} response The decoded response from server\r
3056          * @param {Record/Record{}} rs The records from Store\r
3057          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
3058          */\r
3059         'write'\r
3060     );\r
3061     Ext.data.DataProxy.superclass.constructor.call(this);\r
3062 };\r
3063 \r
3064 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {\r
3065     /**\r
3066      * @cfg {Boolean} restful\r
3067      * <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>\r
3068      * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the\r
3069      * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the\r
3070      * Store is RESTful, there is no need to set this option on the proxy.</p>\r
3071      * <br><p>RESTful implementations enable the serverside framework to automatically route\r
3072      * actions sent to one url based upon the HTTP method, for example:\r
3073      * <pre><code>\r
3074 store: new Ext.data.Store({\r
3075     restful: true,\r
3076     proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users\r
3077     ...\r
3078 )}\r
3079      * </code></pre>\r
3080      * There is no <code>{@link #api}</code> specified in the configuration of the proxy,\r
3081      * all requests will be marshalled to a single RESTful url (/users) so the serverside\r
3082      * framework can inspect the HTTP Method and act accordingly:\r
3083      * <pre>\r
3084 <u>Method</u>   <u>url</u>        <u>action</u>\r
3085 POST     /users     create\r
3086 GET      /users     read\r
3087 PUT      /users/23  update\r
3088 DESTROY  /users/23  delete\r
3089      * </pre></p>\r
3090      */\r
3091     restful: false,\r
3092 \r
3093     /**\r
3094      * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>\r
3095      * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>\r
3096 proxy.setApi({\r
3097     read    : '/users/read',\r
3098     create  : '/users/create',\r
3099     update  : '/users/update',\r
3100     destroy : '/users/destroy'\r
3101 });\r
3102 </code></pre>\r
3103      * <p>If called with two parameters, the first parameter should be a string specifying the API action to\r
3104      * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>\r
3105 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');\r
3106 </code></pre>\r
3107      * @param {String/Object} api An API specification object, or the name of an action.\r
3108      * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.\r
3109      */\r
3110     setApi : function() {\r
3111         if (arguments.length == 1) {\r
3112             var valid = Ext.data.Api.isValid(arguments[0]);\r
3113             if (valid === true) {\r
3114                 this.api = arguments[0];\r
3115             }\r
3116             else {\r
3117                 throw new Ext.data.Api.Error('invalid', valid);\r
3118             }\r
3119         }\r
3120         else if (arguments.length == 2) {\r
3121             if (!Ext.data.Api.isAction(arguments[0])) {\r
3122                 throw new Ext.data.Api.Error('invalid', arguments[0]);\r
3123             }\r
3124             this.api[arguments[0]] = arguments[1];\r
3125         }\r
3126         Ext.data.Api.prepare(this);\r
3127     },\r
3128 \r
3129     /**\r
3130      * Returns true if the specified action is defined as a unique action in the api-config.\r
3131      * request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined\r
3132      * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to\r
3133      * the corresponding code for CRUD action.\r
3134      * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action\r
3135      * @return {Boolean}\r
3136      */\r
3137     isApiAction : function(action) {\r
3138         return (this.api[action]) ? true : false;\r
3139     },\r
3140 \r
3141     /**\r
3142      * All proxy actions are executed through this method.  Automatically fires the "before" + action event\r
3143      * @param {String} action Name of the action\r
3144      * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'\r
3145      * @param {Object} params\r
3146      * @param {Ext.data.DataReader} reader\r
3147      * @param {Function} callback\r
3148      * @param {Object} scope Scope with which to call the callback (defaults to the Proxy object)\r
3149      * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.\r
3150      */\r
3151     request : function(action, rs, params, reader, callback, scope, options) {\r
3152         if (!this.api[action] && !this.load) {\r
3153             throw new Ext.data.DataProxy.Error('action-undefined', action);\r
3154         }\r
3155         params = params || {};\r
3156         if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {\r
3157             this.doRequest.apply(this, arguments);\r
3158         }\r
3159         else {\r
3160             callback.call(scope || this, null, options, false);\r
3161         }\r
3162     },\r
3163 \r
3164 \r
3165     /**\r
3166      * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.\r
3167      * @deprecated\r
3168      * @param {Object} params\r
3169      * @param {Object} reader\r
3170      * @param {Object} callback\r
3171      * @param {Object} scope\r
3172      * @param {Object} arg\r
3173      */\r
3174     load : null,\r
3175 \r
3176     /**\r
3177      * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses\r
3178      * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},\r
3179      * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).\r
3180      */\r
3181     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
3182         // default implementation of doRequest for backwards compatibility with 2.0 proxies.\r
3183         // If we're executing here, the action is probably "load".\r
3184         // Call with the pre-3.0 method signature.\r
3185         this.load(params, reader, callback, scope, options);\r
3186     },\r
3187 \r
3188     /**\r
3189      * buildUrl\r
3190      * Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,\r
3191      * url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an\r
3192      * instance of Ext.data.Record rather than an Array of them.\r
3193      * @param {String} action The api action being executed [read|create|update|destroy]\r
3194      * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.\r
3195      * @return {String} url\r
3196      * @private\r
3197      */\r
3198     buildUrl : function(action, record) {\r
3199         record = record || null;\r
3200         var url = (this.api[action]) ? this.api[action].url : this.url;\r
3201         if (!url) {\r
3202             throw new Ext.data.Api.Error('invalid-url', action);\r
3203         }\r
3204 \r
3205         var format = null;\r
3206         var m = url.match(/(.*)(\.\w+)$/);  // <-- look for urls with "provides" suffix, e.g.: /users.json, /users.xml, etc\r
3207         if (m) {\r
3208             format = m[2];\r
3209             url = m[1];\r
3210         }\r
3211         // prettyUrls is deprectated in favor of restful-config\r
3212         if ((this.prettyUrls === true || this.restful === true) && record instanceof Ext.data.Record && !record.phantom) {\r
3213             url += '/' + record.id;\r
3214         }\r
3215         if (format) {   // <-- append the request format if exists (ie: /users/update/69[.json])\r
3216             url += format;\r
3217         }\r
3218         return url;\r
3219     },\r
3220 \r
3221     /**\r
3222      * Destroys the proxy by purging any event listeners and cancelling any active requests.\r
3223      */\r
3224     destroy: function(){\r
3225         this.purgeListeners();\r
3226     }\r
3227 });\r
3228 \r
3229 /**\r
3230  * @class Ext.data.DataProxy.Error\r
3231  * @extends Ext.Error\r
3232  * DataProxy Error extension.\r
3233  * constructor\r
3234  * @param {String} name\r
3235  * @param {Record/Array[Record]/Array}\r
3236  */\r
3237 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {\r
3238     constructor : function(message, arg) {\r
3239         this.arg = arg;\r
3240         Ext.Error.call(this, message);\r
3241     },\r
3242     name: 'Ext.data.DataProxy'\r
3243 });\r
3244 Ext.apply(Ext.data.DataProxy.Error.prototype, {\r
3245     lang: {\r
3246         'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",\r
3247         'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'\r
3248     }\r
3249 });\r
3250 /**\r
3251  * @class Ext.data.ScriptTagProxy\r
3252  * @extends Ext.data.DataProxy\r
3253  * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain\r
3254  * other than the originating domain of the running page.<br>\r
3255  * <p>\r
3256  * <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain\r
3257  * of the running page, you must use this class, rather than HttpProxy.</b><br>\r
3258  * <p>\r
3259  * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript\r
3260  * source code because it is used as the source inside a &lt;script> tag.<br>\r
3261  * <p>\r
3262  * In order for the browser to process the returned data, the server must wrap the data object\r
3263  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.\r
3264  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy\r
3265  * depending on whether the callback name was passed:\r
3266  * <p>\r
3267  * <pre><code>\r
3268 boolean scriptTag = false;\r
3269 String cb = request.getParameter("callback");\r
3270 if (cb != null) {\r
3271     scriptTag = true;\r
3272     response.setContentType("text/javascript");\r
3273 } else {\r
3274     response.setContentType("application/x-json");\r
3275 }\r
3276 Writer out = response.getWriter();\r
3277 if (scriptTag) {\r
3278     out.write(cb + "(");\r
3279 }\r
3280 out.print(dataBlock.toJsonString());\r
3281 if (scriptTag) {\r
3282     out.write(");");\r
3283 }\r
3284 </code></pre>\r
3285  *\r
3286  * @constructor\r
3287  * @param {Object} config A configuration object.\r
3288  */\r
3289 Ext.data.ScriptTagProxy = function(config){\r
3290     Ext.apply(this, config);\r
3291 \r
3292     Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);\r
3293 \r
3294     this.head = document.getElementsByTagName("head")[0];\r
3295 \r
3296     /**\r
3297      * @event loadexception\r
3298      * <b>Deprecated</b> in favor of 'exception' event.\r
3299      * Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:\r
3300      * <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit\r
3301      * specified by {@link #timeout}.  In this case, this event will be raised and the\r
3302      * fourth parameter (read error) will be null.</li>\r
3303      * <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned\r
3304      * data, but the configured Reader threw an error while reading the data.  In this case, this event will be\r
3305      * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>\r
3306      * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly\r
3307      * on any Store instance.\r
3308      * @param {Object} this\r
3309      * @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load\r
3310      * call timed out, this parameter will be null.\r
3311      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
3312      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.\r
3313      * If the remote request returns success: false, this parameter will be null.\r
3314      */\r
3315 };\r
3316 \r
3317 Ext.data.ScriptTagProxy.TRANS_ID = 1000;\r
3318 \r
3319 Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {\r
3320     /**\r
3321      * @cfg {String} url The URL from which to request the data object.\r
3322      */\r
3323     /**\r
3324      * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.\r
3325      */\r
3326     timeout : 30000,\r
3327     /**\r
3328      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells\r
3329      * the server the name of the callback function set up by the load call to process the returned data object.\r
3330      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate\r
3331      * javascript output which calls this named function passing the data object as its only parameter.\r
3332      */\r
3333     callbackParam : "callback",\r
3334     /**\r
3335      *  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter\r
3336      * name to the request.\r
3337      */\r
3338     nocache : true,\r
3339 \r
3340     /**\r
3341      * HttpProxy implementation of DataProxy#doRequest\r
3342      * @param {String} action\r
3343      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null\r
3344      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
3345      * for the request to the remote server.\r
3346      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
3347      * object into a block of Ext.data.Records.\r
3348      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
3349      * The function must be passed <ul>\r
3350      * <li>The Record block object</li>\r
3351      * <li>The "arg" argument from the load function</li>\r
3352      * <li>A boolean success indicator</li>\r
3353      * </ul>\r
3354      * @param {Object} scope The scope in which to call the callback\r
3355      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
3356      */\r
3357     doRequest : function(action, rs, params, reader, callback, scope, arg) {\r
3358         var p = Ext.urlEncode(Ext.apply(params, this.extraParams));\r
3359 \r
3360         var url = this.buildUrl(action, rs);\r
3361         if (!url) {\r
3362             throw new Ext.data.Api.Error('invalid-url', url);\r
3363         }\r
3364         url = Ext.urlAppend(url, p);\r
3365 \r
3366         if(this.nocache){\r
3367             url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));\r
3368         }\r
3369         var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;\r
3370         var trans = {\r
3371             id : transId,\r
3372             action: action,\r
3373             cb : "stcCallback"+transId,\r
3374             scriptId : "stcScript"+transId,\r
3375             params : params,\r
3376             arg : arg,\r
3377             url : url,\r
3378             callback : callback,\r
3379             scope : scope,\r
3380             reader : reader\r
3381         };\r
3382         window[trans.cb] = this.createCallback(action, rs, trans);\r
3383         url += String.format("&{0}={1}", this.callbackParam, trans.cb);\r
3384         if(this.autoAbort !== false){\r
3385             this.abort();\r
3386         }\r
3387 \r
3388         trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);\r
3389 \r
3390         var script = document.createElement("script");\r
3391         script.setAttribute("src", url);\r
3392         script.setAttribute("type", "text/javascript");\r
3393         script.setAttribute("id", trans.scriptId);\r
3394         this.head.appendChild(script);\r
3395 \r
3396         this.trans = trans;\r
3397     },\r
3398 \r
3399     // @private createCallback\r
3400     createCallback : function(action, rs, trans) {\r
3401         var self = this;\r
3402         return function(res) {\r
3403             self.trans = false;\r
3404             self.destroyTrans(trans, true);\r
3405             if (action === Ext.data.Api.actions.read) {\r
3406                 self.onRead.call(self, action, trans, res);\r
3407             } else {\r
3408                 self.onWrite.call(self, action, trans, res, rs);\r
3409             }\r
3410         };\r
3411     },\r
3412     /**\r
3413      * Callback for read actions\r
3414      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3415      * @param {Object} trans The request transaction object\r
3416      * @param {Object} res The server response\r
3417      * @private\r
3418      */\r
3419     onRead : function(action, trans, res) {\r
3420         var result;\r
3421         try {\r
3422             result = trans.reader.readRecords(res);\r
3423         }catch(e){\r
3424             // @deprecated: fire loadexception\r
3425             this.fireEvent("loadexception", this, trans, res, e);\r
3426 \r
3427             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
3428             trans.callback.call(trans.scope||window, null, trans.arg, false);\r
3429             return;\r
3430         }\r
3431         if (result.success === false) {\r
3432             // @deprecated: fire old loadexception for backwards-compat.\r
3433             this.fireEvent('loadexception', this, trans, res);\r
3434 \r
3435             this.fireEvent('exception', this, 'remote', action, trans, res, null);\r
3436         } else {\r
3437             this.fireEvent("load", this, res, trans.arg);\r
3438         }\r
3439         trans.callback.call(trans.scope||window, result, trans.arg, result.success);\r
3440     },\r
3441     /**\r
3442      * Callback for write actions\r
3443      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3444      * @param {Object} trans The request transaction object\r
3445      * @param {Object} res The server response\r
3446      * @private\r
3447      */\r
3448     onWrite : function(action, trans, res, rs) {\r
3449         var reader = trans.reader;\r
3450         try {\r
3451             // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.\r
3452             reader.readResponse(action, res);\r
3453         } catch (e) {\r
3454             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
3455             trans.callback.call(trans.scope||window, null, res, false);\r
3456             return;\r
3457         }\r
3458         if(!res[reader.meta.successProperty] === true){\r
3459             this.fireEvent('exception', this, 'remote', action, trans, res, rs);\r
3460             trans.callback.call(trans.scope||window, null, res, false);\r
3461             return;\r
3462         }\r
3463         this.fireEvent("write", this, action, res[reader.meta.root], res, rs, trans.arg );\r
3464         trans.callback.call(trans.scope||window, res[reader.meta.root], res, true);\r
3465     },\r
3466 \r
3467     // private\r
3468     isLoading : function(){\r
3469         return this.trans ? true : false;\r
3470     },\r
3471 \r
3472     /**\r
3473      * Abort the current server request.\r
3474      */\r
3475     abort : function(){\r
3476         if(this.isLoading()){\r
3477             this.destroyTrans(this.trans);\r
3478         }\r
3479     },\r
3480 \r
3481     // private\r
3482     destroyTrans : function(trans, isLoaded){\r
3483         this.head.removeChild(document.getElementById(trans.scriptId));\r
3484         clearTimeout(trans.timeoutId);\r
3485         if(isLoaded){\r
3486             window[trans.cb] = undefined;\r
3487             try{\r
3488                 delete window[trans.cb];\r
3489             }catch(e){}\r
3490         }else{\r
3491             // if hasn't been loaded, wait for load to remove it to prevent script error\r
3492             window[trans.cb] = function(){\r
3493                 window[trans.cb] = undefined;\r
3494                 try{\r
3495                     delete window[trans.cb];\r
3496                 }catch(e){}\r
3497             };\r
3498         }\r
3499     },\r
3500 \r
3501     // private\r
3502     handleFailure : function(trans){\r
3503         this.trans = false;\r
3504         this.destroyTrans(trans, false);\r
3505         if (trans.action === Ext.data.Api.actions.read) {\r
3506             // @deprecated firing loadexception\r
3507             this.fireEvent("loadexception", this, null, trans.arg);\r
3508         }\r
3509 \r
3510         this.fireEvent('exception', this, 'response', trans.action, {\r
3511             response: null,\r
3512             options: trans.arg\r
3513         });\r
3514         trans.callback.call(trans.scope||window, null, trans.arg, false);\r
3515     },\r
3516 \r
3517     // inherit docs\r
3518     destroy: function(){\r
3519         this.abort();\r
3520         Ext.data.ScriptTagProxy.superclass.destroy.call(this);\r
3521     }\r
3522 });/**\r
3523  * @class Ext.data.HttpProxy\r
3524  * @extends Ext.data.DataProxy\r
3525  * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same\r
3526  * domain of the originating page.</p>\r
3527  * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other\r
3528  * than the domain from which the running page was served. For cross-domain requests, use a\r
3529  * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>\r
3530  * <p>Be aware that to enable the browser to parse an XML document, the server must set\r
3531  * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>\r
3532  * @constructor\r
3533  * @param {Object} conn\r
3534  * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.\r
3535  * <p>Note that if this HttpProxy is being used by a (@link Ext.data.Store Store}, then the\r
3536  * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>\r
3537  * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,\r
3538  * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be\r
3539  * used to pass parameters known at instantiation time.</p>\r
3540  * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make\r
3541  * the request.</p>\r
3542  */\r
3543 Ext.data.HttpProxy = function(conn){\r
3544     Ext.data.HttpProxy.superclass.constructor.call(this, conn);\r
3545 \r
3546     /**\r
3547      * The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy\r
3548      * uses to make requests to the server. Properties of this object may be changed dynamically to\r
3549      * change the way data is requested.\r
3550      * @property\r
3551      */\r
3552     this.conn = conn;\r
3553 \r
3554     // nullify the connection url.  The url param has been copied to 'this' above.  The connection\r
3555     // url will be set during each execution of doRequest when buildUrl is called.  This makes it easier for users to override the\r
3556     // connection url during beforeaction events (ie: beforeload, beforesave, etc).  The connection url will be nullified\r
3557     // after each request as well.  Url is always re-defined during doRequest.\r
3558     this.conn.url = null;\r
3559 \r
3560     this.useAjax = !conn || !conn.events;\r
3561 \r
3562     //private.  A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]\r
3563     var actions = Ext.data.Api.actions;\r
3564     this.activeRequest = {};\r
3565     for (var verb in actions) {\r
3566         this.activeRequest[actions[verb]] = undefined;\r
3567     }\r
3568 };\r
3569 \r
3570 Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {\r
3571     /**\r
3572      * @cfg {Boolean} restful\r
3573      * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's\r
3574      * {@link Ext.data.Record#id id} will be appended to the url (defaults to <tt>false</tt>).</p><br>\r
3575      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>\r
3576      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the\r
3577      * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>\r
3578      * <p>Some MVC (e.g., Ruby on Rails, Merb and Django) support this style of segment based urls\r
3579      * where the segments in the URL follow the Model-View-Controller approach.</p><pre><code>\r
3580      * someSite.com/controller/action/id\r
3581      * </code></pre>\r
3582      * Where the segments in the url are typically:<div class="mdetail-params"><ul>\r
3583      * <li>The first segment : represents the controller class that should be invoked.</li>\r
3584      * <li>The second segment : represents the class function, or method, that should be called.</li>\r
3585      * <li>The third segment : represents the ID (a variable typically passed to the method).</li>\r
3586      * </ul></div></p>\r
3587      * <p>For example:</p>\r
3588      * <pre><code>\r
3589 api: {\r
3590     load :    '/controller/load',\r
3591     create :  '/controller/new',  // Server MUST return idProperty of new record\r
3592     save :    '/controller/update',\r
3593     destroy : '/controller/destroy_action'\r
3594 }\r
3595 \r
3596 // Alternatively, one can use the object-form to specify each API-action\r
3597 api: {\r
3598     load: {url: 'read.php', method: 'GET'},\r
3599     create: 'create.php',\r
3600     destroy: 'destroy.php',\r
3601     save: 'update.php'\r
3602 }\r
3603      */\r
3604 \r
3605     /**\r
3606      * Return the {@link Ext.data.Connection} object being used by this Proxy.\r
3607      * @return {Connection} The Connection object. This object may be used to subscribe to events on\r
3608      * a finer-grained basis than the DataProxy events.\r
3609      */\r
3610     getConnection : function() {\r
3611         return this.useAjax ? Ext.Ajax : this.conn;\r
3612     },\r
3613 \r
3614     /**\r
3615      * Used for overriding the url used for a single request.  Designed to be called during a beforeaction event.  Calling setUrl\r
3616      * will override any urls set via the api configuration parameter.  Set the optional parameter makePermanent to set the url for\r
3617      * all subsequent requests.  If not set to makePermanent, the next request will use the same url or api configuration defined\r
3618      * in the initial proxy configuration.\r
3619      * @param {String} url\r
3620      * @param {Boolean} makePermanent (Optional) [false]\r
3621      *\r
3622      * (e.g.: beforeload, beforesave, etc).\r
3623      */\r
3624     setUrl : function(url, makePermanent) {\r
3625         this.conn.url = url;\r
3626         if (makePermanent === true) {\r
3627             this.url = url;\r
3628             Ext.data.Api.prepare(this);\r
3629         }\r
3630     },\r
3631 \r
3632     /**\r
3633      * HttpProxy implementation of DataProxy#doRequest\r
3634      * @param {String} action The crud action type (create, read, update, destroy)\r
3635      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
3636      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
3637      * for the request to the remote server.\r
3638      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
3639      * object into a block of Ext.data.Records.\r
3640      * @param {Function} callback\r
3641      * <div class="sub-desc"><p>A function to be called after the request.\r
3642      * The <tt>callback</tt> is passed the following arguments:<ul>\r
3643      * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>\r
3644      * <li><tt>options</tt>: Options object from the action request</li>\r
3645      * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>\r
3646      * @param {Object} scope The scope in which to call the callback\r
3647      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
3648      */\r
3649     doRequest : function(action, rs, params, reader, cb, scope, arg) {\r
3650         var  o = {\r
3651             method: (this.api[action]) ? this.api[action]['method'] : undefined,\r
3652             request: {\r
3653                 callback : cb,\r
3654                 scope : scope,\r
3655                 arg : arg\r
3656             },\r
3657             reader: reader,\r
3658             callback : this.createCallback(action, rs),\r
3659             scope: this\r
3660         };\r
3661         // Sample the request data:  If it's an object, then it hasn't been json-encoded yet.\r
3662         // Transmit data using jsonData config of Ext.Ajax.request\r
3663         if (typeof(params[reader.meta.root]) === 'object') {\r
3664             o.jsonData = params;\r
3665         } else {\r
3666             o.params = params || {};\r
3667         }\r
3668         // Set the connection url.  If this.conn.url is not null here,\r
3669         // the user may have overridden the url during a beforeaction event-handler.\r
3670         // this.conn.url is nullified after each request.\r
3671         if (this.conn.url === null) {\r
3672             this.conn.url = this.buildUrl(action, rs);\r
3673         }\r
3674         else if (this.restful === true && rs instanceof Ext.data.Record && !rs.phantom) {\r
3675             this.conn.url += '/' + rs.id;\r
3676         }\r
3677         if(this.useAjax){\r
3678 \r
3679             Ext.applyIf(o, this.conn);\r
3680 \r
3681             // If a currently running request is found for this action, abort it.\r
3682             if (this.activeRequest[action]) {\r
3683                 // Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array\r
3684                 //Ext.Ajax.abort(this.activeRequest[action]);\r
3685             }\r
3686             this.activeRequest[action] = Ext.Ajax.request(o);\r
3687         }else{\r
3688             this.conn.request(o);\r
3689         }\r
3690         // request is sent, nullify the connection url in preparation for the next request\r
3691         this.conn.url = null;\r
3692     },\r
3693 \r
3694     /**\r
3695      * Returns a callback function for a request.  Note a special case is made for the\r
3696      * read action vs all the others.\r
3697      * @param {String} action [create|update|delete|load]\r
3698      * @param {Ext.data.Record[]} rs The Store-recordset being acted upon\r
3699      * @private\r
3700      */\r
3701     createCallback : function(action, rs) {\r
3702         return function(o, success, response) {\r
3703             this.activeRequest[action] = undefined;\r
3704             if (!success) {\r
3705                 if (action === Ext.data.Api.actions.read) {\r
3706                     // @deprecated: fire loadexception for backwards compat.\r
3707                     this.fireEvent('loadexception', this, o, response);\r
3708                 }\r
3709                 this.fireEvent('exception', this, 'response', action, o, response);\r
3710                 o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
3711                 return;\r
3712             }\r
3713             if (action === Ext.data.Api.actions.read) {\r
3714                 this.onRead(action, o, response);\r
3715             } else {\r
3716                 this.onWrite(action, o, response, rs);\r
3717             }\r
3718         }\r
3719     },\r
3720 \r
3721     /**\r
3722      * Callback for read action\r
3723      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
3724      * @param {Object} o The request transaction object\r
3725      * @param {Object} res The server response\r
3726      * @private\r
3727      */\r
3728     onRead : function(action, o, response) {\r
3729         var result;\r
3730         try {\r
3731             result = o.reader.read(response);\r
3732         }catch(e){\r
3733             // @deprecated: fire old loadexception for backwards-compat.\r
3734             this.fireEvent('loadexception', this, o, response, e);\r
3735             this.fireEvent('exception', this, 'response', action, o, response, e);\r
3736             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
3737             return;\r
3738         }\r
3739         if (result.success === false) {\r
3740             // @deprecated: fire old loadexception for backwards-compat.\r
3741             this.fireEvent('loadexception', this, o, response);\r
3742 \r
3743             // Get DataReader read-back a response-object to pass along to exception event\r
3744             var res = o.reader.readResponse(action, response);\r
3745             this.fireEvent('exception', this, 'remote', action, o, res, null);\r
3746         }\r
3747         else {\r
3748             this.fireEvent('load', this, o, o.request.arg);\r
3749         }\r
3750         o.request.callback.call(o.request.scope, result, o.request.arg, result.success);\r
3751     },\r
3752     /**\r
3753      * Callback for write actions\r
3754      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3755      * @param {Object} trans The request transaction object\r
3756      * @param {Object} res The server response\r
3757      * @private\r
3758      */\r
3759     onWrite : function(action, o, response, rs) {\r
3760         var reader = o.reader;\r
3761         var res;\r
3762         try {\r
3763             res = reader.readResponse(action, response);\r
3764         } catch (e) {\r
3765             this.fireEvent('exception', this, 'response', action, o, response, e);\r
3766             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
3767             return;\r
3768         }\r
3769         if (res[reader.meta.successProperty] === false) {\r
3770             this.fireEvent('exception', this, 'remote', action, o, res, rs);\r
3771         } else {\r
3772             this.fireEvent('write', this, action, res[reader.meta.root], res, rs, o.request.arg);\r
3773         }\r
3774         o.request.callback.call(o.request.scope, res[reader.meta.root], res, res[reader.meta.successProperty]);\r
3775     },\r
3776 \r
3777     // inherit docs\r
3778     destroy: function(){\r
3779         if(!this.useAjax){\r
3780             this.conn.abort();\r
3781         }else if(this.activeRequest){\r
3782             var actions = Ext.data.Api.actions;\r
3783             for (var verb in actions) {\r
3784                 if(this.activeRequest[actions[verb]]){\r
3785                     Ext.Ajax.abort(this.activeRequest[actions[verb]]);\r
3786                 }\r
3787             }\r
3788         }\r
3789         Ext.data.HttpProxy.superclass.destroy.call(this);\r
3790     }\r
3791 });/**\r
3792  * @class Ext.data.MemoryProxy\r
3793  * @extends Ext.data.DataProxy\r
3794  * An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor\r
3795  * to the Reader when its load method is called.\r
3796  * @constructor\r
3797  * @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.\r
3798  */\r
3799 Ext.data.MemoryProxy = function(data){\r
3800     // Must define a dummy api with "read" action to satisfy DataProxy#doRequest and Ext.data.Api#prepare *before* calling super\r
3801     var api = {};\r
3802     api[Ext.data.Api.actions.read] = true;\r
3803     Ext.data.MemoryProxy.superclass.constructor.call(this, {\r
3804         api: api\r
3805     });\r
3806     this.data = data;\r
3807 };\r
3808 \r
3809 Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {\r
3810     /**\r
3811      * @event loadexception\r
3812      * Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed\r
3813      * through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.\r
3814      * @param {Object} this\r
3815      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
3816      * @param {Object} null This parameter does not apply and will always be null for MemoryProxy\r
3817      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data\r
3818      */\r
3819 \r
3820        /**\r
3821      * MemoryProxy implementation of DataProxy#doRequest\r
3822      * @param {String} action\r
3823      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
3824      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
3825      * for the request to the remote server.\r
3826      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
3827      * object into a block of Ext.data.Records.\r
3828      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
3829      * The function must be passed <ul>\r
3830      * <li>The Record block object</li>\r
3831      * <li>The "arg" argument from the load function</li>\r
3832      * <li>A boolean success indicator</li>\r
3833      * </ul>\r
3834      * @param {Object} scope The scope in which to call the callback\r
3835      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
3836      */\r
3837     doRequest : function(action, rs, params, reader, callback, scope, arg) {\r
3838         // No implementation for CRUD in MemoryProxy.  Assumes all actions are 'load'\r
3839         params = params || {};\r
3840         var result;\r
3841         try {\r
3842             result = reader.readRecords(this.data);\r
3843         }catch(e){\r
3844             // @deprecated loadexception\r
3845             this.fireEvent("loadexception", this, null, arg, e);\r
3846 \r
3847             this.fireEvent('exception', this, 'response', action, arg, null, e);\r
3848             callback.call(scope, null, arg, false);\r
3849             return;\r
3850         }\r
3851         callback.call(scope, result, arg, true);\r
3852     }\r
3853 });