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