commit extjs-2.2.1
[extjs.git] / source / data / Store.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\r
10  * @class Ext.data.Store\r
11  * @extends Ext.util.Observable\r
12  * The Store class encapsulates a client side cache of {@link Ext.data.Record Record}\r
13  * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},\r
14  * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}</p>\r
15  * <p>A Store object uses its {@link #proxy configured} implementation of {@link Ext.data.DataProxy DataProxy}\r
16  * to access a data object unless you call {@link #loadData} directly and pass in your data.</p>\r
17  * <p>A Store object has no knowledge of the format of the data returned by the Proxy.</p>\r
18  * <p>A Store object uses its {@link #reader configured} implementation of {@link Ext.data.DataReader DataReader}\r
19  * to create {@link Ext.data.Record Record} instances from the data object. These Records\r
20  * are cached and made available through accessor functions.</p>\r
21  * @constructor\r
22  * Creates a new Store.\r
23  * @param {Object} config A config object containing the objects needed for the Store to access data,\r
24  * and read the data into Records.\r
25  */\r
26 Ext.data.Store = function(config){\r
27     this.data = new Ext.util.MixedCollection(false);\r
28     this.data.getKey = function(o){\r
29         return o.id;\r
30     };\r
31     /**\r
32      * An object containing properties which are used as parameters on any HTTP request.\r
33      * This property can be changed after creating the Store to send different parameters.\r
34      * @property\r
35      */\r
36     this.baseParams = {};\r
37     /**\r
38      * <p>An object containing properties which specify the names of the paging and\r
39      * sorting parameters passed to remote servers when loading blocks of data. By default, this\r
40      * object takes the following form:</p><pre><code>\r
41 {\r
42     start : "start",    // The parameter name which specifies the start row\r
43     limit : "limit",    // The parameter name which specifies number of rows to return\r
44     sort : "sort",      // The parameter name which specifies the column to sort on\r
45     dir : "dir"         // The parameter name which specifies the sort direction\r
46 }\r
47 </code></pre>\r
48      * <p>The server must produce the requested data block upon receipt of these parameter names.\r
49      * If different parameter names are required, this property can be overriden using a configuration\r
50      * property.</p>\r
51      * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this grid uses this property to determine\r
52      * the parameter names to use in its requests.\r
53      * @property\r
54      */\r
55     this.paramNames = {\r
56         "start" : "start",\r
57         "limit" : "limit",\r
58         "sort" : "sort",\r
59         "dir" : "dir"\r
60     };\r
61 \r
62     if(config && config.data){\r
63         this.inlineData = config.data;\r
64         delete config.data;\r
65     }\r
66 \r
67     Ext.apply(this, config);\r
68 \r
69     if(this.url && !this.proxy){\r
70         this.proxy = new Ext.data.HttpProxy({url: this.url});\r
71     }\r
72 \r
73     if(this.reader){ // reader passed\r
74         if(!this.recordType){\r
75             this.recordType = this.reader.recordType;\r
76         }\r
77         if(this.reader.onMetaChange){\r
78             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);\r
79         }\r
80     }\r
81 \r
82     /**\r
83      * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the {@link Ext.data.Reader#Reader Reader}.  Read-only.\r
84      * <p>If the Reader was constructed by passing in an Array of field definition objects, instead of an created\r
85      * Record constructor it will have {@link Ext.data.Record#create created a constructor} from that Array.</p>\r
86      * <p>This property may be used to create new Records of the type held in this Store.</p>\r
87      * @property recordType\r
88      * @type Function\r
89      */\r
90     if(this.recordType){\r
91         /**\r
92          * A MixedCollection containing the defined {@link Ext.data.Field Field}s for the Records stored in this Store.  Read-only.\r
93          * @property fields\r
94          * @type Ext.util.MixedCollection\r
95          */\r
96         this.fields = this.recordType.prototype.fields;\r
97     }\r
98     this.modified = [];\r
99 \r
100     this.addEvents(\r
101         /**\r
102          * @event datachanged\r
103          * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a \r
104          * widget that is using this Store as a Record cache should refresh its view.\r
105          * @param {Store} this\r
106          */\r
107         'datachanged',\r
108         /**\r
109          * @event metachange\r
110          * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.\r
111          * @param {Store} this\r
112          * @param {Object} meta The JSON metadata\r
113          */\r
114         'metachange',\r
115         /**\r
116          * @event add\r
117          * Fires when Records have been added to the Store\r
118          * @param {Store} this\r
119          * @param {Ext.data.Record[]} records The array of Records added\r
120          * @param {Number} index The index at which the record(s) were added\r
121          */\r
122         'add',\r
123         /**\r
124          * @event remove\r
125          * Fires when a Record has been removed from the Store\r
126          * @param {Store} this\r
127          * @param {Ext.data.Record} record The Record that was removed\r
128          * @param {Number} index The index at which the record was removed\r
129          */\r
130         'remove',\r
131         /**\r
132          * @event update\r
133          * Fires when a Record has been updated\r
134          * @param {Store} this\r
135          * @param {Ext.data.Record} record The Record that was updated\r
136          * @param {String} operation The update operation being performed.  Value may be one of:\r
137          * <pre><code>\r
138  Ext.data.Record.EDIT\r
139  Ext.data.Record.REJECT\r
140  Ext.data.Record.COMMIT\r
141          * </code></pre>\r
142          */\r
143         'update',\r
144         /**\r
145          * @event clear\r
146          * Fires when the data cache has been cleared.\r
147          * @param {Store} this\r
148          */\r
149         'clear',\r
150         /**\r
151          * @event beforeload\r
152          * Fires before a request is made for a new data object.  If the beforeload handler returns false\r
153          * the load action will be canceled.\r
154          * @param {Store} this\r
155          * @param {Object} options The loading options that were specified (see {@link #load} for details)\r
156          */\r
157         'beforeload',\r
158         /**\r
159          * @event load\r
160          * Fires after a new set of Records has been loaded.\r
161          * @param {Store} this\r
162          * @param {Ext.data.Record[]} records The Records that were loaded\r
163          * @param {Object} options The loading options that were specified (see {@link #load} for details)\r
164          */\r
165         'load',\r
166         /**\r
167          * @event loadexception\r
168          * Fires if an exception occurs in the Proxy during loading.\r
169          * Called with the signature of the Proxy's "loadexception" event.\r
170          */\r
171         'loadexception'\r
172     );\r
173 \r
174     if(this.proxy){\r
175         this.relayEvents(this.proxy,  ["loadexception"]);\r
176     }\r
177 \r
178     this.sortToggle = {};\r
179     if(this.sortInfo){\r
180         this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);\r
181     }\r
182 \r
183     Ext.data.Store.superclass.constructor.call(this);\r
184 \r
185     if(this.storeId || this.id){\r
186         Ext.StoreMgr.register(this);\r
187     }\r
188     if(this.inlineData){\r
189         this.loadData(this.inlineData);\r
190         delete this.inlineData;\r
191     }else if(this.autoLoad){\r
192         this.load.defer(10, this, [\r
193             typeof this.autoLoad == 'object' ?\r
194                 this.autoLoad : undefined]);\r
195     }\r
196 };\r
197 Ext.extend(Ext.data.Store, Ext.util.Observable, {\r
198     /**\r
199     * @cfg {String} storeId If passed, the id to use to register with the StoreMgr\r
200     */\r
201     /**\r
202     * @cfg {String} url If passed, an HttpProxy is created for the passed URL\r
203     */\r
204     /**\r
205     * @cfg {Boolean/Object} autoLoad If passed, this store's load method is automatically called after creation with the autoLoad object\r
206     */\r
207     /**\r
208     * @cfg {Ext.data.DataProxy} proxy The Proxy object which provides access to a data object.\r
209     */\r
210     /**\r
211     * @cfg {Array} data Inline data to be loaded when the store is initialized.\r
212     */\r
213     /**\r
214     * @cfg {Ext.data.DataReader} reader The DataReader object which processes the data object and returns\r
215     * an Array of Ext.data.Record objects which are cached keyed by their <em>id</em> property.\r
216     */\r
217     /**\r
218     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters\r
219     * on any HTTP request\r
220     */\r
221     /**\r
222     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"} to \r
223     * specify the sort order in the request of a remote Store's {@link #load} operation.  Note that for\r
224     * local sorting, the direction property is case-sensitive.\r
225     */\r
226     /**\r
227     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the\r
228     * Proxy to provide a refreshed version of the data object in sorted order, as\r
229     * opposed to sorting the Record cache in place (defaults to false).\r
230     * <p>If remote sorting is specified, then clicking on a column header causes the\r
231     * current page to be requested from the server with the addition of the following\r
232     * two parameters:\r
233     * <div class="mdetail-params"><ul>\r
234     * <li><b>sort</b> : String<p class="sub-desc">The name (as specified in\r
235     * the Record's Field definition) of the field to sort on.</p></li>\r
236     * <li><b>dir</b> : String<p class="sub-desc">The direction of the sort, "ASC" or "DESC" (case-sensitive).</p></li>\r
237     * </ul></div></p>\r
238     */\r
239     remoteSort : false,\r
240 \r
241     /**\r
242     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is\r
243      * loaded or when a record is removed. (defaults to false).\r
244     */\r
245     pruneModifiedRecords : false,\r
246 \r
247     /**\r
248      * Contains the last options object used as the parameter to the load method. See {@link #load}\r
249      * for the details of what this may contain. This may be useful for accessing any params which\r
250      * were used to load the current Record cache.\r
251      * @property\r
252      */\r
253    lastOptions : null,\r
254 \r
255     destroy : function(){\r
256         if(this.storeId || this.id){\r
257             Ext.StoreMgr.unregister(this);\r
258         }\r
259         this.data = null;\r
260         this.purgeListeners();\r
261     },\r
262 \r
263     /**\r
264      * Add Records to the Store and fires the {@link #add} event.\r
265      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.\r
266      */\r
267     add : function(records){\r
268         records = [].concat(records);\r
269         if(records.length < 1){\r
270             return;\r
271         }\r
272         for(var i = 0, len = records.length; i < len; i++){\r
273             records[i].join(this);\r
274         }\r
275         var index = this.data.length;\r
276         this.data.addAll(records);\r
277         if(this.snapshot){\r
278             this.snapshot.addAll(records);\r
279         }\r
280         this.fireEvent("add", this, records, index);\r
281     },\r
282 \r
283     /**\r
284      * (Local sort only) Inserts the passed Record into the Store at the index where it\r
285      * should go based on the current sort information.\r
286      * @param {Ext.data.Record} record\r
287      */\r
288     addSorted : function(record){\r
289         var index = this.findInsertIndex(record);\r
290         this.insert(index, record);\r
291     },\r
292 \r
293     /**\r
294      * Remove a Record from the Store and fires the {@link #remove} event.\r
295      * @param {Ext.data.Record} record The Ext.data.Record object to remove from the cache.\r
296      */\r
297     remove : function(record){\r
298         var index = this.data.indexOf(record);\r
299         this.data.removeAt(index);\r
300         if(this.pruneModifiedRecords){\r
301             this.modified.remove(record);\r
302         }\r
303         if(this.snapshot){\r
304             this.snapshot.remove(record);\r
305         }\r
306         this.fireEvent("remove", this, record, index);\r
307     },\r
308     \r
309     /**\r
310      * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.\r
311      * @param {Number} index The index of the record to remove.\r
312      */\r
313     removeAt : function(index){\r
314         this.remove(this.getAt(index));    \r
315     },\r
316 \r
317     /**\r
318      * Remove all Records from the Store and fires the {@link #clear} event.\r
319      */\r
320     removeAll : function(){\r
321         this.data.clear();\r
322         if(this.snapshot){\r
323             this.snapshot.clear();\r
324         }\r
325         if(this.pruneModifiedRecords){\r
326             this.modified = [];\r
327         }\r
328         this.fireEvent("clear", this);\r
329     },\r
330 \r
331     /**\r
332      * Inserts Records into the Store at the given index and fires the {@link #add} event.\r
333      * @param {Number} index The start index at which to insert the passed Records.\r
334      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.\r
335      */\r
336     insert : function(index, records){\r
337         records = [].concat(records);\r
338         for(var i = 0, len = records.length; i < len; i++){\r
339             this.data.insert(index, records[i]);\r
340             records[i].join(this);\r
341         }\r
342         this.fireEvent("add", this, records, index);\r
343     },\r
344 \r
345     /**\r
346      * Get the index within the cache of the passed Record.\r
347      * @param {Ext.data.Record} record The Ext.data.Record object to find.\r
348      * @return {Number} The index of the passed Record. Returns -1 if not found.\r
349      */\r
350     indexOf : function(record){\r
351         return this.data.indexOf(record);\r
352     },\r
353 \r
354     /**\r
355      * Get the index within the cache of the Record with the passed id.\r
356      * @param {String} id The id of the Record to find.\r
357      * @return {Number} The index of the Record. Returns -1 if not found.\r
358      */\r
359     indexOfId : function(id){\r
360         return this.data.indexOfKey(id);\r
361     },\r
362 \r
363     /**\r
364      * Get the Record with the specified id.\r
365      * @param {String} id The id of the Record to find.\r
366      * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.\r
367      */\r
368     getById : function(id){\r
369         return this.data.key(id);\r
370     },\r
371 \r
372     /**\r
373      * Get the Record at the specified index.\r
374      * @param {Number} index The index of the Record to find.\r
375      * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.\r
376      */\r
377     getAt : function(index){\r
378         return this.data.itemAt(index);\r
379     },\r
380 \r
381     /**\r
382      * Returns a range of Records between specified indices.\r
383      * @param {Number} startIndex (optional) The starting index (defaults to 0)\r
384      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)\r
385      * @return {Ext.data.Record[]} An array of Records\r
386      */\r
387     getRange : function(start, end){\r
388         return this.data.getRange(start, end);\r
389     },\r
390 \r
391     // private\r
392     storeOptions : function(o){\r
393         o = Ext.apply({}, o);\r
394         delete o.callback;\r
395         delete o.scope;\r
396         this.lastOptions = o;\r
397     },\r
398 \r
399     /**\r
400      * Loads the Record cache from the configured Proxy using the configured Reader.\r
401      * <p>If using remote paging, then the first load call must specify the <tt>start</tt>\r
402      * and <tt>limit</tt> properties in the options.params property to establish the initial\r
403      * position within the dataset, and the number of Records to cache on each read from the Proxy.</p>\r
404      * <p><b>It is important to note that for remote data sources, loading is asynchronous,\r
405      * and this call will return before the new data has been loaded. Perform any post-processing\r
406      * in a callback function, or in a "load" event handler.</b></p>\r
407      * @param {Object} options An object containing properties which control loading options:<ul>\r
408      * <li><b>params</b> :Object<p class="sub-desc">An object containing properties to pass as HTTP parameters to a remote data source.</p></li>\r
409      * <li><b>callback</b> : Function<p class="sub-desc">A function to be called after the Records have been loaded. The callback is\r
410      * passed the following arguments:<ul>\r
411      * <li>r : Ext.data.Record[]</li>\r
412      * <li>options: Options object from the load call</li>\r
413      * <li>success: Boolean success indicator</li></ul></p></li>\r
414      * <li><b>scope</b> : Object<p class="sub-desc">Scope with which to call the callback (defaults to the Store object)</p></li>\r
415      * <li><b>add</b> : Boolean<p class="sub-desc">Indicator to append loaded records rather than replace the current cache.</p></li>\r
416      * </ul>\r
417      * @return {Boolean} Whether the load fired (if beforeload failed).\r
418      */\r
419     load : function(options){\r
420         options = options || {};\r
421         if(this.fireEvent("beforeload", this, options) !== false){\r
422             this.storeOptions(options);\r
423             var p = Ext.apply(options.params || {}, this.baseParams);\r
424             if(this.sortInfo && this.remoteSort){\r
425                 var pn = this.paramNames;\r
426                 p[pn["sort"]] = this.sortInfo.field;\r
427                 p[pn["dir"]] = this.sortInfo.direction;\r
428             }\r
429             this.proxy.load(p, this.reader, this.loadRecords, this, options);\r
430             return true;\r
431         } else {\r
432           return false;\r
433         }\r
434     },\r
435 \r
436     /**\r
437      * <p>Reloads the Record cache from the configured Proxy using the configured Reader and\r
438      * the options from the last load operation performed.</p>\r
439      * <p><b>It is important to note that for remote data sources, loading is asynchronous,\r
440      * and this call will return before the new data has been loaded. Perform any post-processing\r
441      * in a callback function, or in a "load" event handler.</b></p>\r
442      * @param {Object} options (optional) An object containing loading options which may override the options\r
443      * used in the last load operation. See {@link #load} for details (defaults to null, in which case\r
444      * the most recently used options are reused).\r
445      */\r
446     reload : function(options){\r
447         this.load(Ext.applyIf(options||{}, this.lastOptions));\r
448     },\r
449 \r
450     // private\r
451     // Called as a callback by the Reader during a load operation.\r
452     loadRecords : function(o, options, success){\r
453         if(!o || success === false){\r
454             if(success !== false){\r
455                 this.fireEvent("load", this, [], options);\r
456             }\r
457             if(options.callback){\r
458                 options.callback.call(options.scope || this, [], options, false);\r
459             }\r
460             return;\r
461         }\r
462         var r = o.records, t = o.totalRecords || r.length;\r
463         if(!options || options.add !== true){\r
464             if(this.pruneModifiedRecords){\r
465                 this.modified = [];\r
466             }\r
467             for(var i = 0, len = r.length; i < len; i++){\r
468                 r[i].join(this);\r
469             }\r
470             if(this.snapshot){\r
471                 this.data = this.snapshot;\r
472                 delete this.snapshot;\r
473             }\r
474             this.data.clear();\r
475             this.data.addAll(r);\r
476             this.totalLength = t;\r
477             this.applySort();\r
478             this.fireEvent("datachanged", this);\r
479         }else{\r
480             this.totalLength = Math.max(t, this.data.length+r.length);\r
481             this.add(r);\r
482         }\r
483         this.fireEvent("load", this, r, options);\r
484         if(options.callback){\r
485             options.callback.call(options.scope || this, r, options, true);\r
486         }\r
487     },\r
488 \r
489     /**\r
490      * Loads data from a passed data block and fires the {@link #load} event. A Reader which understands the format of the data\r
491      * must have been configured in the constructor.\r
492      * @param {Object} data The data block from which to read the Records.  The format of the data expected\r
493      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.\r
494      * @param {Boolean} add (Optional) True to add the new Records rather than replace the existing cache. <b>Remember that\r
495      * Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records with ids which are already present in\r
496      * the Store will <i>replace</i> existing Records. Records with new, unique ids will be added.</b>\r
497      */\r
498     loadData : function(o, append){\r
499         var r = this.reader.readRecords(o);\r
500         this.loadRecords(r, {add: append}, true);\r
501     },\r
502 \r
503     /**\r
504      * Gets the number of cached records.\r
505      * <p>If using paging, this may not be the total size of the dataset. If the data object\r
506      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns\r
507      * the dataset size.</p>\r
508      * @return {Number} The number of Records in the Store's cache.\r
509      */\r
510     getCount : function(){\r
511         return this.data.length || 0;\r
512     },\r
513 \r
514     /**\r
515      * Gets the total number of records in the dataset as returned by the server.\r
516      * <p>If using paging, for this to be accurate, the data object used by the Reader must contain\r
517      * the dataset size. For remote data sources, this is provided by a query on the server.</p>\r
518      * @return {Number} The number of Records as specified in the data object passed to the Reader\r
519      * by the Proxy\r
520      * <p><b>This value is not updated when changing the contents of the Store locally.</b></p>\r
521      */\r
522     getTotalCount : function(){\r
523         return this.totalLength || 0;\r
524     },\r
525 \r
526     /**\r
527      * Returns an object describing the current sort state of this Store.\r
528      * @return {Object} The sort state of the Store. An object with two properties:<ul>\r
529      * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>\r
530      * <li><b>direction : String<p class="sub-desc">The sort order, "ASC" or "DESC" (case-sensitive).</p></li>\r
531      * </ul>\r
532      */\r
533     getSortState : function(){\r
534         return this.sortInfo;\r
535     },\r
536 \r
537     // private\r
538     applySort : function(){\r
539         if(this.sortInfo && !this.remoteSort){\r
540             var s = this.sortInfo, f = s.field;\r
541             this.sortData(f, s.direction);\r
542         }\r
543     },\r
544 \r
545     // private\r
546     sortData : function(f, direction){\r
547         direction = direction || 'ASC';\r
548         var st = this.fields.get(f).sortType;\r
549         var fn = function(r1, r2){\r
550             var v1 = st(r1.data[f]), v2 = st(r2.data[f]);\r
551             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);\r
552         };\r
553         this.data.sort(direction, fn);\r
554         if(this.snapshot && this.snapshot != this.data){\r
555             this.snapshot.sort(direction, fn);\r
556         }\r
557     },\r
558 \r
559     /**\r
560      * Sets the default sort column and order to be used by the next load operation.\r
561      * @param {String} fieldName The name of the field to sort by.\r
562      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (case-sensitive, defaults to "ASC")\r
563      */\r
564     setDefaultSort : function(field, dir){\r
565         dir = dir ? dir.toUpperCase() : "ASC";\r
566         this.sortInfo = {field: field, direction: dir};\r
567         this.sortToggle[field] = dir;\r
568     },\r
569 \r
570     /**\r
571      * Sort the Records.\r
572      * If remote sorting is used, the sort is performed on the server, and the cache is\r
573      * reloaded. If local sorting is used, the cache is sorted internally.\r
574      * @param {String} fieldName The name of the field to sort by.\r
575      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (case-sensitive, defaults to "ASC")\r
576      */\r
577     sort : function(fieldName, dir){\r
578         var f = this.fields.get(fieldName);\r
579         if(!f){\r
580             return false;\r
581         }\r
582         if(!dir){\r
583             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir\r
584                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");\r
585             }else{\r
586                 dir = f.sortDir;\r
587             }\r
588         }\r
589         var st = (this.sortToggle) ? this.sortToggle[f.name] : null;\r
590         var si = (this.sortInfo) ? this.sortInfo : null;\r
591 \r
592         this.sortToggle[f.name] = dir;\r
593         this.sortInfo = {field: f.name, direction: dir};\r
594         if(!this.remoteSort){\r
595             this.applySort();\r
596             this.fireEvent("datachanged", this);\r
597         }else{\r
598             if (!this.load(this.lastOptions)) {\r
599                 if (st) {\r
600                     this.sortToggle[f.name] = st;\r
601                 }\r
602                 if (si) {\r
603                     this.sortInfo = si;\r
604                 }\r
605             }\r
606         }\r
607     },\r
608 \r
609     /**\r
610      * Calls the specified function for each of the Records in the cache.\r
611      * @param {Function} fn The function to call. The Record is passed as the first parameter.\r
612      * Returning <tt>false</tt> aborts and exits the iteration.\r
613      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).\r
614      */\r
615     each : function(fn, scope){\r
616         this.data.each(fn, scope);\r
617     },\r
618 \r
619     /**\r
620      * Gets all records modified since the last commit.  Modified records are persisted across load operations\r
621      * (e.g., during paging).\r
622      * @return {Ext.data.Record[]} An array of Records containing outstanding modifications.\r
623      */\r
624     getModifiedRecords : function(){\r
625         return this.modified;\r
626     },\r
627 \r
628     // private\r
629     createFilterFn : function(property, value, anyMatch, caseSensitive){\r
630         if(Ext.isEmpty(value, false)){\r
631             return false;\r
632         }\r
633         value = this.data.createValueMatcher(value, anyMatch, caseSensitive);\r
634         return function(r){\r
635             return value.test(r.data[property]);\r
636         };\r
637     },\r
638 \r
639     /**\r
640      * Sums the value of <i>property</i> for each record between start and end and returns the result.\r
641      * @param {String} property A field on your records\r
642      * @param {Number} start The record index to start at (defaults to 0)\r
643      * @param {Number} end The last record index to include (defaults to length - 1)\r
644      * @return {Number} The sum\r
645      */\r
646     sum : function(property, start, end){\r
647         var rs = this.data.items, v = 0;\r
648         start = start || 0;\r
649         end = (end || end === 0) ? end : rs.length-1;\r
650 \r
651         for(var i = start; i <= end; i++){\r
652             v += (rs[i].data[property] || 0);\r
653         }\r
654         return v;\r
655     },\r
656 \r
657     /**\r
658      * Filter the records by a specified property.\r
659      * @param {String} field A field on your records\r
660      * @param {String/RegExp} value Either a string that the field\r
661      * should begin with, or a RegExp to test against the field.\r
662      * @param {Boolean} anyMatch (optional) True to match any part not just the beginning\r
663      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison\r
664      */\r
665     filter : function(property, value, anyMatch, caseSensitive){\r
666         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);\r
667         return fn ? this.filterBy(fn) : this.clearFilter();\r
668     },\r
669 \r
670     /**\r
671      * Filter by a function. The specified function will be called for each\r
672      * Record in this Store. If the function returns <tt>true</tt> the Record is included,\r
673      * otherwise it is filtered out.\r
674      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>\r
675      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}\r
676      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>\r
677      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>\r
678      * </ul>\r
679      * @param {Object} scope (optional) The scope of the function (defaults to this)\r
680      */\r
681     filterBy : function(fn, scope){\r
682         this.snapshot = this.snapshot || this.data;\r
683         this.data = this.queryBy(fn, scope||this);\r
684         this.fireEvent("datachanged", this);\r
685     },\r
686 \r
687     /**\r
688      * Query the records by a specified property.\r
689      * @param {String} field A field on your records\r
690      * @param {String/RegExp} value Either a string that the field\r
691      * should begin with, or a RegExp to test against the field.\r
692      * @param {Boolean} anyMatch (optional) True to match any part not just the beginning\r
693      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison\r
694      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records\r
695      */\r
696     query : function(property, value, anyMatch, caseSensitive){\r
697         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);\r
698         return fn ? this.queryBy(fn) : this.data.clone();\r
699     },\r
700 \r
701     /**\r
702      * Query the cached records in this Store using a filtering function. The specified function\r
703      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is\r
704      * included in the results.\r
705      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>\r
706      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}\r
707      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>\r
708      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>\r
709      * </ul>\r
710      * @param {Object} scope (optional) The scope of the function (defaults to this)\r
711      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records\r
712      **/\r
713     queryBy : function(fn, scope){\r
714         var data = this.snapshot || this.data;\r
715         return data.filterBy(fn, scope||this);\r
716     },\r
717 \r
718     /**\r
719      * Finds the index of the first matching record in this store by a specific property/value.\r
720      * @param {String} property A property on your objects\r
721      * @param {String/RegExp} value Either a string that the property value\r
722      * should begin with, or a RegExp to test against the property.\r
723      * @param {Number} startIndex (optional) The index to start searching at\r
724      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning\r
725      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison\r
726      * @return {Number} The matched index or -1\r
727      */\r
728     find : function(property, value, start, anyMatch, caseSensitive){\r
729         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);\r
730         return fn ? this.data.findIndexBy(fn, null, start) : -1;\r
731     },\r
732 \r
733     /**\r
734      * Find the index of the first matching Record in this Store by a function.\r
735      * If the function returns <tt>true</tt> it is considered a match.\r
736      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>\r
737      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}\r
738      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>\r
739      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>\r
740      * </ul>\r
741      * @param {Object} scope (optional) The scope of the function (defaults to this)\r
742      * @param {Number} startIndex (optional) The index to start searching at\r
743      * @return {Number} The matched index or -1\r
744      */\r
745     findBy : function(fn, scope, start){\r
746         return this.data.findIndexBy(fn, scope, start);\r
747     },\r
748 \r
749     /**\r
750      * Collects unique values for a particular dataIndex from this store.\r
751      * @param {String} dataIndex The property to collect\r
752      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values\r
753      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered\r
754      * @return {Array} An array of the unique values\r
755      **/\r
756     collect : function(dataIndex, allowNull, bypassFilter){\r
757         var d = (bypassFilter === true && this.snapshot) ?\r
758                 this.snapshot.items : this.data.items;\r
759         var v, sv, r = [], l = {};\r
760         for(var i = 0, len = d.length; i < len; i++){\r
761             v = d[i].data[dataIndex];\r
762             sv = String(v);\r
763             if((allowNull || !Ext.isEmpty(v)) && !l[sv]){\r
764                 l[sv] = true;\r
765                 r[r.length] = v;\r
766             }\r
767         }\r
768         return r;\r
769     },\r
770 \r
771     /**\r
772      * Revert to a view of the Record cache with no filtering applied.\r
773      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners\r
774      */\r
775     clearFilter : function(suppressEvent){\r
776         if(this.isFiltered()){\r
777             this.data = this.snapshot;\r
778             delete this.snapshot;\r
779             if(suppressEvent !== true){\r
780                 this.fireEvent("datachanged", this);\r
781             }\r
782         }\r
783     },\r
784 \r
785     /**\r
786      * Returns true if this store is currently filtered\r
787      * @return {Boolean}\r
788      */\r
789     isFiltered : function(){\r
790         return this.snapshot && this.snapshot != this.data;\r
791     },\r
792 \r
793     // private\r
794     afterEdit : function(record){\r
795         if(this.modified.indexOf(record) == -1){\r
796             this.modified.push(record);\r
797         }\r
798         this.fireEvent("update", this, record, Ext.data.Record.EDIT);\r
799     },\r
800 \r
801     // private\r
802     afterReject : function(record){\r
803         this.modified.remove(record);\r
804         this.fireEvent("update", this, record, Ext.data.Record.REJECT);\r
805     },\r
806 \r
807     // private\r
808     afterCommit : function(record){\r
809         this.modified.remove(record);\r
810         this.fireEvent("update", this, record, Ext.data.Record.COMMIT);\r
811     },\r
812 \r
813     /**\r
814      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the\r
815      * Store's "update" event, and perform updating when the third parameter is Ext.data.Record.COMMIT.\r
816      */\r
817     commitChanges : function(){\r
818         var m = this.modified.slice(0);\r
819         this.modified = [];\r
820         for(var i = 0, len = m.length; i < len; i++){\r
821             m[i].commit();\r
822         }\r
823     },\r
824 \r
825     /**\r
826      * Cancel outstanding changes on all changed records.\r
827      */\r
828     rejectChanges : function(){\r
829         var m = this.modified.slice(0);\r
830         this.modified = [];\r
831         for(var i = 0, len = m.length; i < len; i++){\r
832             m[i].reject();\r
833         }\r
834     },\r
835 \r
836     // private\r
837     onMetaChange : function(meta, rtype, o){\r
838         this.recordType = rtype;\r
839         this.fields = rtype.prototype.fields;\r
840         delete this.snapshot;\r
841         this.sortInfo = meta.sortInfo;\r
842         this.modified = [];\r
843         this.fireEvent('metachange', this, this.reader.meta);\r
844     },\r
845 \r
846     // private\r
847     findInsertIndex : function(record){\r
848         this.suspendEvents();\r
849         var data = this.data.clone();\r
850         this.data.add(record);\r
851         this.applySort();\r
852         var index = this.data.indexOf(record);\r
853         this.data = data;\r
854         this.resumeEvents();\r
855         return index;\r
856     }\r
857 });