4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-data-Store'>/**
19 </span> * @author Ed Spencer
20 * @class Ext.data.Store
21 * @extends Ext.data.AbstractStore
23 * <p>The Store class encapsulates a client side cache of {@link Ext.data.Model Model} objects. Stores load
24 * data via a {@link Ext.data.proxy.Proxy Proxy}, and also provide functions for {@link #sort sorting},
25 * {@link #filter filtering} and querying the {@link Ext.data.Model model} instances contained within it.</p>
27 * <p>Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data:</p>
29 <pre><code>
30 // Set up a {@link Ext.data.Model model} to use in our Store
32 extend: 'Ext.data.Model',
34 {name: 'firstName', type: 'string'},
35 {name: 'lastName', type: 'string'},
36 {name: 'age', type: 'int'},
37 {name: 'eyeColor', type: 'string'}
41 var myStore = new Ext.data.Store({
53 </code></pre>
55 * <p>In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy
56 * to use a {@link Ext.data.reader.Json JsonReader} to parse the response from the server into Model object -
57 * {@link Ext.data.reader.Json see the docs on JsonReader} for details.</p>
59 * <p><u>Inline data</u></p>
61 * <p>Stores can also load data inline. Internally, Store converts each of the objects we pass in as {@link #data}
62 * into Model instances:</p>
64 <pre><code>
68 {firstName: 'Ed', lastName: 'Spencer'},
69 {firstName: 'Tommy', lastName: 'Maintz'},
70 {firstName: 'Aaron', lastName: 'Conran'},
71 {firstName: 'Jamie', lastName: 'Avins'}
74 </code></pre>
76 * <p>Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need
77 * to be processed by a {@link Ext.data.reader.Reader reader}). If your inline data requires processing to decode the data structure,
78 * use a {@link Ext.data.proxy.Memory MemoryProxy} instead (see the {@link Ext.data.proxy.Memory MemoryProxy} docs for an example).</p>
80 * <p>Additional data can also be loaded locally using {@link #add}.</p>
82 * <p><u>Loading Nested Data</u></p>
84 * <p>Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders.
85 * Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset
86 * and allow the Reader to automatically populate the associated models. Below is a brief example, see the {@link Ext.data.reader.Reader} intro
87 * docs for a full explanation:</p>
89 <pre><code>
90 var store = new Ext.data.Store({
92 model: "User",
102 </code></pre>
104 * <p>Which would consume a response like this:</p>
106 <pre><code>
111 "name": "Ed",
112 "orders": [
115 "total": 10.76,
116 "status": "invoiced"
120 "total": 13.45,
121 "status": "shipped"
127 </code></pre>
129 * <p>See the {@link Ext.data.reader.Reader} intro docs for a full explanation.</p>
131 * <p><u>Filtering and Sorting</u></p>
133 * <p>Stores can be sorted and filtered - in both cases either remotely or locally. The {@link #sorters} and {@link #filters} are
134 * held inside {@link Ext.util.MixedCollection MixedCollection} instances to make them easy to manage. Usually it is sufficient to
135 * either just specify sorters and filters in the Store configuration or call {@link #sort} or {@link #filter}:
137 <pre><code>
138 var store = new Ext.data.Store({
146 property : 'firstName',
153 property: 'firstName',
158 </code></pre>
160 * <p>The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting
161 * and filtering are both performed locally by the Store - see {@link #remoteSort} and {@link #remoteFilter} to allow the server to
162 * perform these operations instead.</p>
164 * <p>Filtering and sorting after the Store has been instantiated is also easy. Calling {@link #filter} adds another filter to the Store
165 * and automatically filters the dataset (calling {@link #filter} with no arguments simply re-applies all existing filters). Note that by
166 * default {@link #sortOnFilter} is set to true, which means that your sorters are automatically reapplied if using local sorting.</p>
168 <pre><code>
169 store.filter('eyeColor', 'Brown');
170 </code></pre>
172 * <p>Change the sorting at any time by calling {@link #sort}:</p>
174 <pre><code>
175 store.sort('height', 'ASC');
176 </code></pre>
178 * <p>Note that all existing sorters will be removed in favor of the new sorter data (if {@link #sort} is called with no arguments,
179 * the existing sorters are just reapplied instead of being removed). To keep existing sorters and add new ones, just add them
180 * to the MixedCollection:</p>
182 <pre><code>
183 store.sorters.add(new Ext.util.Sorter({
184 property : 'shoeSize',
189 </code></pre>
191 * <p><u>Registering with StoreManager</u></p>
193 * <p>Any Store that is instantiated with a {@link #storeId} will automatically be registed with the {@link Ext.data.StoreManager StoreManager}.
194 * This makes it easy to reuse the same store in multiple views:</p>
196 <pre><code>
197 //this store can be used several times
200 storeId: 'usersStore'
206 //other config goes here
212 //other config goes here
214 </code></pre>
216 * <p><u>Further Reading</u></p>
218 * <p>Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these
219 * pieces and how they fit together, see:</p>
221 * <ul style="list-style-type: disc; padding-left: 25px">
222 * <li>{@link Ext.data.proxy.Proxy Proxy} - overview of what Proxies are and how they are used</li>
223 * <li>{@link Ext.data.Model Model} - the core class in the data package</li>
224 * <li>{@link Ext.data.reader.Reader Reader} - used by any subclass of {@link Ext.data.proxy.Server ServerProxy} to read a response</li>
228 Ext.define('Ext.data.Store', {
229 extend: 'Ext.data.AbstractStore',
231 alias: 'store.store',
233 requires: ['Ext.ModelManager', 'Ext.data.Model', 'Ext.util.Grouper'],
234 uses: ['Ext.data.proxy.Memory'],
236 <span id='Ext-data-Store-cfg-remoteSort'> /**
237 </span> * @cfg {Boolean} remoteSort
238 * True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to <tt>false</tt>.
242 <span id='Ext-data-Store-cfg-remoteFilter'> /**
243 </span> * @cfg {Boolean} remoteFilter
244 * True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to <tt>false</tt>.
248 <span id='Ext-data-Store-cfg-remoteGroup'> /**
249 </span> * @cfg {Boolean} remoteGroup
250 * True if the grouping should apply on the server side, false if it is local only (defaults to false). If the
251 * grouping is local, it can be applied immediately to the data. If it is remote, then it will simply act as a
252 * helper, automatically sending the grouping information to the server.
256 <span id='Ext-data-Store-cfg-proxy'> /**
257 </span> * @cfg {String/Ext.data.proxy.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config
258 * object or a Proxy instance - see {@link #setProxy} for details.
261 <span id='Ext-data-Store-cfg-data'> /**
262 </span> * @cfg {Array} data Optional array of Model instances or data objects to load locally. See "Inline data" above for details.
265 <span id='Ext-data-Store-cfg-model'> /**
266 </span> * @cfg {String} model The {@link Ext.data.Model} associated with this store
269 <span id='Ext-data-Store-property-groupField'> /**
270 </span> * The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the
271 * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single
272 * level of grouping, and groups can be fetched via the {@link #getGroups} method.
273 * @property groupField
276 groupField: undefined,
278 <span id='Ext-data-Store-property-groupDir'> /**
279 </span> * The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC"
283 groupDir: "ASC",
285 <span id='Ext-data-Store-cfg-pageSize'> /**
286 </span> * @cfg {Number} pageSize
287 * The number of records considered to form a 'page'. This is used to power the built-in
288 * paging using the nextPage and previousPage functions. Defaults to 25.
292 <span id='Ext-data-Store-property-currentPage'> /**
293 </span> * The page that the Store has most recently loaded (see {@link #loadPage})
294 * @property currentPage
299 <span id='Ext-data-Store-cfg-clearOnPageLoad'> /**
300 </span> * @cfg {Boolean} clearOnPageLoad True to empty the store when loading another page via {@link #loadPage},
301 * {@link #nextPage} or {@link #previousPage} (defaults to true). Setting to false keeps existing records, allowing
302 * large data sets to be loaded one page at a time but rendered all together.
304 clearOnPageLoad: true,
306 <span id='Ext-data-Store-property-loading'> /**
307 </span> * True if the Store is currently loading via its Proxy
314 <span id='Ext-data-Store-cfg-sortOnFilter'> /**
315 </span> * @cfg {Boolean} sortOnFilter For local filtering only, causes {@link #sort} to be called whenever {@link #filter} is called,
316 * causing the sorters to be reapplied after filtering. Defaults to true
320 <span id='Ext-data-Store-cfg-buffered'> /**
321 </span> * @cfg {Boolean} buffered
322 * Allow the store to buffer and pre-fetch pages of records. This is to be used in conjunction with a view will
323 * tell the store to pre-fetch records ahead of a time.
327 <span id='Ext-data-Store-cfg-purgePageCount'> /**
328 </span> * @cfg {Number} purgePageCount
329 * The number of pages to keep in the cache before purging additional records. A value of 0 indicates to never purge the prefetched data.
330 * This option is only relevant when the {@link #buffered} option is set to true.
336 <span id='Ext-data-Store-method-constructor'> /**
337 </span> * Creates the store.
338 * @param {Object} config (optional) Config object
340 constructor: function(config) {
341 config = config || {};
344 groupers = config.groupers || me.groupers,
345 groupField = config.groupField || me.groupField,
349 if (config.buffered || me.buffered) {
350 me.prefetchData = Ext.create('Ext.util.MixedCollection', false, function(record) {
353 me.pendingRequests = [];
354 me.pagesRequested = [];
356 me.sortOnLoad = false;
357 me.filterOnLoad = false;
361 <span id='Ext-data-Store-event-beforeprefetch'> /**
362 </span> * @event beforeprefetch
363 * Fires before a prefetch occurs. Return false to cancel.
364 * @param {Ext.data.store} this
365 * @param {Ext.data.Operation} operation The associated operation
368 <span id='Ext-data-Store-event-groupchange'> /**
369 </span> * @event groupchange
370 * Fired whenever the grouping in the grid changes
371 * @param {Ext.data.Store} store The store
372 * @param {Array} groupers The array of grouper objects
375 <span id='Ext-data-Store-event-load'> /**
376 </span> * @event load
377 * Fires whenever records have been prefetched
378 * @param {Ext.data.store} this
379 * @param {Array} records An array of records
380 * @param {Boolean} successful True if the operation was successful.
381 * @param {Ext.data.Operation} operation The associated operation
385 data = config.data || me.data;
387 <span id='Ext-data-Store-property-data'> /**
388 </span> * The MixedCollection that holds this store's local cache of records
390 * @type Ext.util.MixedCollection
392 me.data = Ext.create('Ext.util.MixedCollection', false, function(record) {
393 return record.internalId;
397 me.inlineData = data;
401 if (!groupers && groupField) {
403 property : groupField,
404 direction: config.groupDir || me.groupDir
407 delete config.groupers;
409 <span id='Ext-data-Store-property-groupers'> /**
410 </span> * The collection of {@link Ext.util.Grouper Groupers} currently applied to this Store
412 * @type Ext.util.MixedCollection
414 me.groupers = Ext.create('Ext.util.MixedCollection');
415 me.groupers.addAll(me.decodeGroupers(groupers));
417 this.callParent([config]);
418 // don't use *config* anymore from here on... use *me* instead...
420 if (me.groupers.items.length) {
421 me.sort(me.groupers.items, 'prepend', false);
425 data = me.inlineData;
428 if (proxy instanceof Ext.data.proxy.Memory) {
432 me.add.apply(me, data);
436 delete me.inlineData;
437 } else if (me.autoLoad) {
438 Ext.defer(me.load, 10, me, [typeof me.autoLoad === 'object' ? me.autoLoad: undefined]);
439 // Remove the defer call, we may need reinstate this at some point, but currently it's not obvious why it's here.
440 // this.load(typeof this.autoLoad == 'object' ? this.autoLoad : undefined);
444 onBeforeSort: function() {
445 this.sort(this.groupers.items, 'prepend', false);
448 <span id='Ext-data-Store-method-decodeGroupers'> /**
450 * Normalizes an array of grouper objects, ensuring that they are all Ext.util.Grouper instances
451 * @param {Array} groupers The groupers array
452 * @return {Array} Array of Ext.util.Grouper objects
454 decodeGroupers: function(groupers) {
455 if (!Ext.isArray(groupers)) {
456 if (groupers === undefined) {
459 groupers = [groupers];
463 var length = groupers.length,
464 Grouper = Ext.util.Grouper,
467 for (i = 0; i < length; i++) {
468 config = groupers[i];
470 if (!(config instanceof Grouper)) {
471 if (Ext.isString(config)) {
477 Ext.applyIf(config, {
479 direction: "ASC"
482 //support for 3.x style sorters where a function can be defined as 'fn'
484 config.sorterFn = config.fn;
487 //support a function to be passed as a sorter definition
488 if (typeof config == 'function') {
494 groupers[i] = new Grouper(config);
501 <span id='Ext-data-Store-method-group'> /**
502 </span> * Group data in the store
503 * @param {String|Array} groupers Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model},
504 * or an Array of grouper configurations.
505 * @param {String} direction The overall direction to group the data by. Defaults to "ASC".
507 group: function(groupers, direction) {
512 if (Ext.isArray(groupers)) {
513 newGroupers = groupers;
514 } else if (Ext.isObject(groupers)) {
515 newGroupers = [groupers];
516 } else if (Ext.isString(groupers)) {
517 grouper = me.groupers.get(groupers);
524 newGroupers = [grouper];
525 } else if (direction === undefined) {
528 grouper.setDirection(direction);
532 if (newGroupers && newGroupers.length) {
533 newGroupers = me.decodeGroupers(newGroupers);
535 me.groupers.addAll(newGroupers);
538 if (me.remoteGroup) {
541 callback: me.fireGroupChange
545 me.fireEvent('groupchange', me, me.groupers);
549 <span id='Ext-data-Store-method-clearGrouping'> /**
550 </span> * Clear any groupers in the store
552 clearGrouping: function(){
554 // Clear any groupers we pushed on to the sorters
555 me.groupers.each(function(grouper){
556 me.sorters.remove(grouper);
559 if (me.remoteGroup) {
562 callback: me.fireGroupChange
566 me.fireEvent('groupchange', me, me.groupers);
570 <span id='Ext-data-Store-method-isGrouped'> /**
571 </span> * Checks if the store is currently grouped
572 * @return {Boolean} True if the store is grouped.
574 isGrouped: function() {
575 return this.groupers.getCount() > 0;
578 <span id='Ext-data-Store-method-fireGroupChange'> /**
579 </span> * Fires the groupchange event. Abstracted out so we can use it
583 fireGroupChange: function(){
584 this.fireEvent('groupchange', this, this.groupers);
587 <span id='Ext-data-Store-method-getGroups'> /**
588 </span> * Returns an object containing the result of applying grouping to the records in this store. See {@link #groupField},
589 * {@link #groupDir} and {@link #getGroupString}. Example for a store containing records with a color field:
590 <pre><code>
591 var myStore = new Ext.data.Store({
596 myStore.getGroups(); //returns:
601 //all records where the color field is 'yellow'
607 //all records where the color field is 'red'
611 </code></pre>
612 * @param {String} groupName (Optional) Pass in an optional groupName argument to access a specific group as defined by {@link #getGroupString}
613 * @return {Array} The grouped data
615 getGroups: function(requestGroupString) {
616 var records = this.data.items,
617 length = records.length,
625 for (i = 0; i < length; i++) {
627 groupStr = this.getGroupString(record);
628 group = pointers[groupStr];
630 if (group === undefined) {
637 pointers[groupStr] = group;
640 group.children.push(record);
643 return requestGroupString ? pointers[requestGroupString] : groups;
646 <span id='Ext-data-Store-method-getGroupsForGrouper'> /**
648 * For a given set of records and a Grouper, returns an array of arrays - each of which is the set of records
649 * matching a certain group.
651 getGroupsForGrouper: function(records, grouper) {
652 var length = records.length,
660 for (i = 0; i < length; i++) {
662 newValue = grouper.getGroupString(record);
664 if (newValue !== oldValue) {
673 group.records.push(record);
681 <span id='Ext-data-Store-method-getGroupsForGrouperIndex'> /**
683 * This is used recursively to gather the records into the configured Groupers. The data MUST have been sorted for
684 * this to work properly (see {@link #getGroupData} and {@link #getGroupsForGrouper}) Most of the work is done by
685 * {@link #getGroupsForGrouper} - this function largely just handles the recursion.
686 * @param {Array} records The set or subset of records to group
687 * @param {Number} grouperIndex The grouper index to retrieve
688 * @return {Array} The grouped records
690 getGroupsForGrouperIndex: function(records, grouperIndex) {
692 groupers = me.groupers,
693 grouper = groupers.getAt(grouperIndex),
694 groups = me.getGroupsForGrouper(records, grouper),
695 length = groups.length,
698 if (grouperIndex + 1 < groupers.length) {
699 for (i = 0; i < length; i++) {
700 groups[i].children = me.getGroupsForGrouperIndex(groups[i].records, grouperIndex + 1);
704 for (i = 0; i < length; i++) {
705 groups[i].depth = grouperIndex;
711 <span id='Ext-data-Store-method-getGroupData'> /**
713 * <p>Returns records grouped by the configured {@link #groupers grouper} configuration. Sample return value (in
714 * this case grouping by genre and then author in a fictional books dataset):</p>
715 <pre><code>
721 //book1, book2, book3, book4
741 </code></pre>
742 * @param {Boolean} sort True to call {@link #sort} before finding groups. Sorting is required to make grouping
743 * function correctly so this should only be set to false if the Store is known to already be sorted correctly
745 * @return {Array} The group data
747 getGroupData: function(sort) {
749 if (sort !== false) {
753 return me.getGroupsForGrouperIndex(me.data.items, 0);
756 <span id='Ext-data-Store-method-getGroupString'> /**
757 </span> * <p>Returns the string to group on for a given model instance. The default implementation of this method returns
758 * the model's {@link #groupField}, but this can be overridden to group by an arbitrary string. For example, to
759 * group by the first letter of a model's 'name' field, use the following code:</p>
760 <pre><code>
763 getGroupString: function(instance) {
764 return instance.get('name')[0];
767 </code></pre>
768 * @param {Ext.data.Model} instance The model instance
769 * @return {String} The string to compare when forming groups
771 getGroupString: function(instance) {
772 var group = this.groupers.first();
774 return instance.get(group.property);
778 <span id='Ext-data-Store-method-insert'> /**
779 </span> * Inserts Model instances into the Store at the given index and fires the {@link #add} event.
780 * See also <code>{@link #add}</code>.
781 * @param {Number} index The start index at which to insert the passed Records.
782 * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache.
784 insert: function(index, records) {
791 records = [].concat(records);
792 for (i = 0, len = records.length; i < len; i++) {
793 record = me.createModel(records[i]);
794 record.set(me.modelDefaults);
795 // reassign the model in the array in case it wasn't created yet
798 me.data.insert(index + i, record);
801 sync = sync || record.phantom === true;
805 me.snapshot.addAll(records);
808 me.fireEvent('add', me, records, index);
809 me.fireEvent('datachanged', me);
810 if (me.autoSync && sync) {
815 <span id='Ext-data-Store-method-add'> /**
816 </span> * Adds Model instances to the Store by instantiating them based on a JavaScript object. When adding already-
817 * instantiated Models, use {@link #insert} instead. The instances will be added at the end of the existing collection.
818 * This method accepts either a single argument array of Model instances or any number of model instance arguments.
821 <pre><code>
822 myStore.add({some: 'data'}, {some: 'other data'});
823 </code></pre>
825 * @param {Object} data The data for each model
826 * @return {Array} The array of newly created model instances
828 add: function(records) {
829 //accept both a single-argument array of records, or any number of record arguments
830 if (!Ext.isArray(records)) {
831 records = Array.prototype.slice.apply(arguments);
836 length = records.length,
839 for (; i < length; i++) {
840 record = me.createModel(records[i]);
841 // reassign the model in the array in case it wasn't created yet
845 me.insert(me.data.length, records);
850 <span id='Ext-data-Store-method-createModel'> /**
851 </span> * Converts a literal to a model, if it's not a model already
853 * @param record {Ext.data.Model/Object} The record to create
854 * @return {Ext.data.Model}
856 createModel: function(record) {
857 if (!record.isModel) {
858 record = Ext.ModelManager.create(record, this.model);
864 <span id='Ext-data-Store-method-each'> /**
865 </span> * Calls the specified function for each of the {@link Ext.data.Model Records} in the cache.
866 * @param {Function} fn The function to call. The {@link Ext.data.Model Record} is passed as the first parameter.
867 * Returning <tt>false</tt> aborts and exits the iteration.
868 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
869 * Defaults to the current {@link Ext.data.Model Record} in the iteration.
871 each: function(fn, scope) {
872 this.data.each(fn, scope);
875 <span id='Ext-data-Store-method-remove'> /**
876 </span> * Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
877 * 'datachanged' event after removal.
878 * @param {Ext.data.Model/Array} records The Ext.data.Model instance or array of instances to remove
880 remove: function(records, /* private */ isMove) {
881 if (!Ext.isArray(records)) {
886 * Pass the isMove parameter if we know we're going to be re-inserting this record
888 isMove = isMove === true;
892 length = records.length,
897 for (; i < length; i++) {
899 index = me.data.indexOf(record);
902 me.snapshot.remove(record);
906 isPhantom = record.phantom === true;
907 if (!isMove && !isPhantom) {
908 // don't push phantom records onto removed
909 me.removed.push(record);
913 me.data.remove(record);
914 sync = sync || !isPhantom;
916 me.fireEvent('remove', me, record, index);
920 me.fireEvent('datachanged', me);
921 if (!isMove && me.autoSync && sync) {
926 <span id='Ext-data-Store-method-removeAt'> /**
927 </span> * Removes the model instance at the given index
928 * @param {Number} index The record index
930 removeAt: function(index) {
931 var record = this.getAt(index);
938 <span id='Ext-data-Store-method-load'> /**
939 </span> * <p>Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an
940 * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved
941 * instances into the Store and calling an optional callback if required. Example usage:</p>
943 <pre><code>
946 callback: function(records, operation, success) {
947 //the {@link Ext.data.Operation operation} object contains all of the details of the load operation
948 console.log(records);
951 </code></pre>
953 * <p>If the callback scope does not need to be set, a function can simply be passed:</p>
955 <pre><code>
956 store.load(function(records, operation, success) {
957 console.log('loaded records');
959 </code></pre>
961 * @param {Object/Function} options Optional config object, passed into the Ext.data.Operation object before loading.
963 load: function(options) {
966 options = options || {};
968 if (Ext.isFunction(options)) {
974 Ext.applyIf(options, {
975 groupers: me.groupers.items,
976 page: me.currentPage,
977 start: (me.currentPage - 1) * me.pageSize,
982 return me.callParent([options]);
985 <span id='Ext-data-Store-method-onProxyLoad'> /**
987 * Called internally when a Proxy has completed a load request
989 onProxyLoad: function(operation) {
991 resultSet = operation.getResultSet(),
992 records = operation.getRecords(),
993 successful = operation.wasSuccessful();
996 me.totalCount = resultSet.total;
1000 me.loadRecords(records, operation);
1004 me.fireEvent('load', me, records, successful);
1006 //TODO: deprecate this event, it should always have been 'load' instead. 'load' is now documented, 'read' is not.
1007 //People are definitely using this so can't deprecate safely until 2.x
1008 me.fireEvent('read', me, records, operation.wasSuccessful());
1010 //this is a callback that would have been passed to the 'read' function and is optional
1011 Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
1014 <span id='Ext-data-Store-method-onCreateRecords'> /**
1015 </span> * Create any new records when a write is returned from the server.
1017 * @param {Array} records The array of new records
1018 * @param {Ext.data.Operation} operation The operation that just completed
1019 * @param {Boolean} success True if the operation was successful
1021 onCreateRecords: function(records, operation, success) {
1025 snapshot = this.snapshot,
1026 length = records.length,
1027 originalRecords = operation.records,
1033 * Loop over each record returned from the server. Assume they are
1034 * returned in order of how they were sent. If we find a matching
1035 * record, replace it with the newly created one.
1037 for (; i < length; ++i) {
1038 record = records[i];
1039 original = originalRecords[i];
1041 index = data.indexOf(original);
1042 if (index > -1) {
1043 data.removeAt(index);
1044 data.insert(index, record);
1047 index = snapshot.indexOf(original);
1048 if (index > -1) {
1049 snapshot.removeAt(index);
1050 snapshot.insert(index, record);
1053 record.phantom = false;
1060 <span id='Ext-data-Store-method-onUpdateRecords'> /**
1061 </span> * Update any records when a write is returned from the server.
1063 * @param {Array} records The array of updated records
1064 * @param {Ext.data.Operation} operation The operation that just completed
1065 * @param {Boolean} success True if the operation was successful
1067 onUpdateRecords: function(records, operation, success){
1070 length = records.length,
1072 snapshot = this.snapshot,
1075 for (; i < length; ++i) {
1076 record = records[i];
1077 data.replace(record);
1079 snapshot.replace(record);
1086 <span id='Ext-data-Store-method-onDestroyRecords'> /**
1087 </span> * Remove any records when a write is returned from the server.
1089 * @param {Array} records The array of removed records
1090 * @param {Ext.data.Operation} operation The operation that just completed
1091 * @param {Boolean} success True if the operation was successful
1093 onDestroyRecords: function(records, operation, success){
1097 length = records.length,
1099 snapshot = me.snapshot,
1102 for (; i < length; ++i) {
1103 record = records[i];
1105 data.remove(record);
1107 snapshot.remove(record);
1115 getNewRecords: function() {
1116 return this.data.filterBy(this.filterNew).items;
1120 getUpdatedRecords: function() {
1121 return this.data.filterBy(this.filterUpdated).items;
1124 <span id='Ext-data-Store-method-filter'> /**
1125 </span> * Filters the loaded set of records by a given set of filters.
1126 * @param {Mixed} filters The set of filters to apply to the data. These are stored internally on the store,
1127 * but the filtering itself is done on the Store's {@link Ext.util.MixedCollection MixedCollection}. See
1128 * MixedCollection's {@link Ext.util.MixedCollection#filter filter} method for filter syntax. Alternatively,
1129 * pass in a property string
1130 * @param {String} value Optional value to filter by (only if using a property string as the first argument)
1132 filter: function(filters, value) {
1133 if (Ext.isString(filters)) {
1141 decoded = me.decodeFilters(filters),
1143 doLocalSort = me.sortOnFilter && !me.remoteSort,
1144 length = decoded.length;
1146 for (; i < length; i++) {
1147 me.filters.replace(decoded[i]);
1150 if (me.remoteFilter) {
1151 //the load function will pick up the new filters and request the filtered data from the proxy
1154 <span id='Ext-data-Store-property-snapshot'> /**
1155 </span> * A pristine (unfiltered) collection of the records in this store. This is used to reinstate
1156 * records when a filter is removed or changed
1157 * @property snapshot
1158 * @type Ext.util.MixedCollection
1160 if (me.filters.getCount()) {
1161 me.snapshot = me.snapshot || me.data.clone();
1162 me.data = me.data.filter(me.filters.items);
1167 // fire datachanged event if it hasn't already been fired by doSort
1168 if (!doLocalSort || me.sorters.length < 1) {
1169 me.fireEvent('datachanged', me);
1175 <span id='Ext-data-Store-method-clearFilter'> /**
1176 </span> * Revert to a view of the Record cache with no filtering applied.
1177 * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1178 * {@link #datachanged} event.
1180 clearFilter: function(suppressEvent) {
1185 if (me.remoteFilter) {
1187 } else if (me.isFiltered()) {
1188 me.data = me.snapshot.clone();
1191 if (suppressEvent !== true) {
1192 me.fireEvent('datachanged', me);
1197 <span id='Ext-data-Store-method-isFiltered'> /**
1198 </span> * Returns true if this store is currently filtered
1201 isFiltered: function() {
1202 var snapshot = this.snapshot;
1203 return !! snapshot && snapshot !== this.data;
1206 <span id='Ext-data-Store-method-filterBy'> /**
1207 </span> * Filter by a function. The specified function will be called for each
1208 * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1209 * otherwise it is filtered out.
1210 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1211 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1212 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1213 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1215 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1217 filterBy: function(fn, scope) {
1220 me.snapshot = me.snapshot || me.data.clone();
1221 me.data = me.queryBy(fn, scope || me);
1222 me.fireEvent('datachanged', me);
1225 <span id='Ext-data-Store-method-queryBy'> /**
1226 </span> * Query the cached records in this Store using a filtering function. The specified function
1227 * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1228 * included in the results.
1229 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1230 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1231 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1232 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1234 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1235 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1237 queryBy: function(fn, scope) {
1239 data = me.snapshot || me.data;
1240 return data.filterBy(fn, scope || me);
1243 <span id='Ext-data-Store-method-loadData'> /**
1244 </span> * Loads an array of data straight into the Store
1245 * @param {Array} data Array of data to load. Any non-model instances will be cast into model instances first
1246 * @param {Boolean} append True to add the records to the existing records in the store, false to remove the old ones first
1248 loadData: function(data, append) {
1249 var model = this.model,
1250 length = data.length,
1254 //make sure each data element is an Ext.data.Model instance
1255 for (i = 0; i < length; i++) {
1258 if (! (record instanceof Ext.data.Model)) {
1259 data[i] = Ext.ModelManager.create(record, model);
1263 this.loadRecords(data, {addRecords: append});
1266 <span id='Ext-data-Store-method-loadRecords'> /**
1267 </span> * Loads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually
1268 * be called internally when loading from the {@link Ext.data.proxy.Proxy Proxy}, when adding records manually use {@link #add} instead
1269 * @param {Array} records The array of records to load
1270 * @param {Object} options {addRecords: true} to add these records to the existing records, false to remove the Store's existing records first
1272 loadRecords: function(records, options) {
1275 length = records.length;
1277 options = options || {};
1280 if (!options.addRecords) {
1285 me.data.addAll(records);
1287 //FIXME: this is not a good solution. Ed Spencer is totally responsible for this and should be forced to fix it immediately.
1288 for (; i < length; i++) {
1289 if (options.start !== undefined) {
1290 records[i].index = options.start + i;
1293 records[i].join(me);
1297 * this rather inelegant suspension and resumption of events is required because both the filter and sort functions
1298 * fire an additional datachanged event, which is not wanted. Ideally we would do this a different way. The first
1299 * datachanged event is fired by the call to this.add, above.
1303 if (me.filterOnLoad && !me.remoteFilter) {
1307 if (me.sortOnLoad && !me.remoteSort) {
1312 me.fireEvent('datachanged', me, records);
1316 <span id='Ext-data-Store-method-loadPage'> /**
1317 </span> * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal
1318 * load operation, passing in calculated 'start' and 'limit' params
1319 * @param {Number} page The number of the page to load
1321 loadPage: function(page) {
1324 me.currentPage = page;
1328 start: (page - 1) * me.pageSize,
1330 addRecords: !me.clearOnPageLoad
1334 <span id='Ext-data-Store-method-nextPage'> /**
1335 </span> * Loads the next 'page' in the current data set
1337 nextPage: function() {
1338 this.loadPage(this.currentPage + 1);
1341 <span id='Ext-data-Store-method-previousPage'> /**
1342 </span> * Loads the previous 'page' in the current data set
1344 previousPage: function() {
1345 this.loadPage(this.currentPage - 1);
1349 clearData: function() {
1350 this.data.each(function(record) {
1358 <span id='Ext-data-Store-method-prefetch'> /**
1359 </span> * Prefetches data the Store using its configured {@link #proxy}.
1360 * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
1363 prefetch: function(options) {
1366 requestId = me.getRequestId();
1368 options = options || {};
1370 Ext.applyIf(options, {
1372 filters: me.filters.items,
1373 sorters: me.sorters.items,
1374 requestId: requestId
1376 me.pendingRequests.push(requestId);
1378 operation = Ext.create('Ext.data.Operation', options);
1380 // HACK to implement loadMask support.
1381 //if (operation.blocking) {
1382 // me.fireEvent('beforeload', me, operation);
1384 if (me.fireEvent('beforeprefetch', me, operation) !== false) {
1386 me.proxy.read(operation, me.onProxyPrefetch, me);
1392 <span id='Ext-data-Store-method-prefetchPage'> /**
1393 </span> * Prefetches a page of data.
1394 * @param {Number} page The page to prefetch
1395 * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
1399 prefetchPage: function(page, options) {
1401 pageSize = me.pageSize,
1402 start = (page - 1) * me.pageSize,
1403 end = start + pageSize;
1405 // Currently not requesting this page and range isn't already satisified
1406 if (Ext.Array.indexOf(me.pagesRequested, page) === -1 && !me.rangeSatisfied(start, end)) {
1407 options = options || {};
1408 me.pagesRequested.push(page);
1409 Ext.applyIf(options, {
1413 callback: me.onWaitForGuarantee,
1417 me.prefetch(options);
1422 <span id='Ext-data-Store-method-getRequestId'> /**
1423 </span> * Returns a unique requestId to track requests.
1426 getRequestId: function() {
1427 this.requestSeed = this.requestSeed || 1;
1428 return this.requestSeed++;
1431 <span id='Ext-data-Store-method-onProxyPrefetch'> /**
1432 </span> * Handles a success pre-fetch
1434 * @param {Ext.data.Operation} operation The operation that completed
1436 onProxyPrefetch: function(operation) {
1438 resultSet = operation.getResultSet(),
1439 records = operation.getRecords(),
1441 successful = operation.wasSuccessful();
1444 me.totalCount = resultSet.total;
1445 me.fireEvent('totalcountchange', me.totalCount);
1449 me.cacheRecords(records, operation);
1451 Ext.Array.remove(me.pendingRequests, operation.requestId);
1452 if (operation.page) {
1453 Ext.Array.remove(me.pagesRequested, operation.page);
1457 me.fireEvent('prefetch', me, records, successful, operation);
1459 // HACK to support loadMask
1460 if (operation.blocking) {
1461 me.fireEvent('load', me, records, successful);
1464 //this is a callback that would have been passed to the 'read' function and is optional
1465 Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
1468 <span id='Ext-data-Store-method-cacheRecords'> /**
1469 </span> * Caches the records in the prefetch and stripes them with their server-side
1472 * @param {Array} records The records to cache
1473 * @param {Ext.data.Operation} The associated operation
1475 cacheRecords: function(records, operation) {
1478 length = records.length,
1479 start = operation ? operation.start : 0;
1481 if (!Ext.isDefined(me.totalCount)) {
1482 me.totalCount = records.length;
1483 me.fireEvent('totalcountchange', me.totalCount);
1486 for (; i < length; i++) {
1487 // this is the true index, not the viewIndex
1488 records[i].index = start + i;
1491 me.prefetchData.addAll(records);
1492 if (me.purgePageCount) {
1499 <span id='Ext-data-Store-method-purgeRecords'> /**
1500 </span> * Purge the least recently used records in the prefetch if the purgeCount
1501 * has been exceeded.
1503 purgeRecords: function() {
1505 prefetchCount = me.prefetchData.getCount(),
1506 purgeCount = me.purgePageCount * me.pageSize,
1507 numRecordsToPurge = prefetchCount - purgeCount - 1,
1510 for (; i <= numRecordsToPurge; i++) {
1511 me.prefetchData.removeAt(0);
1515 <span id='Ext-data-Store-method-rangeSatisfied'> /**
1516 </span> * Determines if the range has already been satisfied in the prefetchData.
1518 * @param {Number} start The start index
1519 * @param {Number} end The end index in the range
1521 rangeSatisfied: function(start, end) {
1526 for (; i < end; i++) {
1527 if (!me.prefetchData.getByKey(i)) {
1530 if (end - i > me.pageSize) {
1531 Ext.Error.raise("A single page prefetch could never satisfy this request.");
1540 <span id='Ext-data-Store-method-getPageFromRecordIndex'> /**
1541 </span> * Determines the page from a record index
1542 * @param {Number} index The record index
1543 * @return {Number} The page the record belongs to
1545 getPageFromRecordIndex: function(index) {
1546 return Math.floor(index / this.pageSize) + 1;
1549 <span id='Ext-data-Store-method-onGuaranteedRange'> /**
1550 </span> * Handles a guaranteed range being loaded
1553 onGuaranteedRange: function() {
1555 totalCount = me.getTotalCount(),
1556 start = me.requestStart,
1557 end = ((totalCount - 1) < me.requestEnd) ? totalCount - 1 : me.requestEnd,
1563 if (start > end) {
1564 Ext.Error.raise("Start (" + start + ") was greater than end (" + end + ")");
1568 if (start !== me.guaranteedStart && end !== me.guaranteedEnd) {
1569 me.guaranteedStart = start;
1570 me.guaranteedEnd = end;
1572 for (; i <= end; i++) {
1573 record = me.prefetchData.getByKey(i);
1576 Ext.Error.raise("Record was not found and store said it was guaranteed");
1581 me.fireEvent('guaranteedrange', range, start, end);
1583 me.cb.call(me.scope || me, range);
1590 // hack to support loadmask
1593 this.fireEvent('beforeload');
1596 // hack to support loadmask
1597 unmask: function() {
1599 this.fireEvent('load');
1603 <span id='Ext-data-Store-method-hasPendingRequests'> /**
1604 </span> * Returns the number of pending requests out.
1606 hasPendingRequests: function() {
1607 return this.pendingRequests.length;
1611 // wait until all requests finish, until guaranteeing the range.
1612 onWaitForGuarantee: function() {
1613 if (!this.hasPendingRequests()) {
1614 this.onGuaranteedRange();
1618 <span id='Ext-data-Store-method-guaranteeRange'> /**
1619 </span> * Guarantee a specific range, this will load the store with a range (that
1620 * must be the pageSize or smaller) and take care of any loading that may
1623 guaranteeRange: function(start, end, cb, scope) {
1625 if (start && end) {
1626 if (end - start > this.pageSize) {
1630 pageSize: this.pageSize,
1631 msg: "Requested a bigger range than the specified pageSize"
1637 end = (end > this.totalCount) ? this.totalCount - 1 : end;
1641 prefetchData = me.prefetchData,
1643 startLoaded = !!prefetchData.getByKey(start),
1644 endLoaded = !!prefetchData.getByKey(end),
1645 startPage = me.getPageFromRecordIndex(start),
1646 endPage = me.getPageFromRecordIndex(end);
1651 me.requestStart = start;
1652 me.requestEnd = end;
1653 // neither beginning or end are loaded
1654 if (!startLoaded || !endLoaded) {
1655 // same page, lets load it
1656 if (startPage === endPage) {
1658 me.prefetchPage(startPage, {
1660 callback: me.onWaitForGuarantee,
1663 // need to load two pages
1666 me.prefetchPage(startPage, {
1668 callback: me.onWaitForGuarantee,
1671 me.prefetchPage(endPage, {
1673 callback: me.onWaitForGuarantee,
1677 // Request was already satisfied via the prefetch
1679 me.onGuaranteedRange();
1683 // because prefetchData is stored by index
1684 // this invalidates all of the prefetchedData
1687 prefetchData = me.prefetchData,
1694 if (me.remoteSort) {
1695 prefetchData.clear();
1696 me.callParent(arguments);
1698 sorters = me.getSorters();
1699 start = me.guaranteedStart;
1700 end = me.guaranteedEnd;
1702 if (sorters.length) {
1703 prefetchData.sort(sorters);
1704 range = prefetchData.getRange();
1705 prefetchData.clear();
1706 me.cacheRecords(range);
1707 delete me.guaranteedStart;
1708 delete me.guaranteedEnd;
1709 me.guaranteeRange(start, end);
1711 me.callParent(arguments);
1714 me.callParent(arguments);
1718 // overriden to provide striping of the indexes as sorting occurs.
1719 // this cannot be done inside of sort because datachanged has already
1720 // fired and will trigger a repaint of the bound view.
1721 doSort: function(sorterFn) {
1723 if (me.remoteSort) {
1724 //the load function will pick up the new sorters and request the sorted data from the proxy
1727 me.data.sortBy(sorterFn);
1729 var range = me.getRange(),
1732 for (; i < ln; i++) {
1736 me.fireEvent('datachanged', me);
1740 <span id='Ext-data-Store-method-find'> /**
1741 </span> * Finds the index of the first matching Record in this store by a specific field value.
1742 * @param {String} fieldName The name of the Record field to test.
1743 * @param {String/RegExp} value Either a string that the field value
1744 * should begin with, or a RegExp to test against the field.
1745 * @param {Number} startIndex (optional) The index to start searching at
1746 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1747 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1748 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1749 * @return {Number} The matched index or -1
1751 find: function(property, value, start, anyMatch, caseSensitive, exactMatch) {
1752 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
1753 return fn ? this.data.findIndexBy(fn, null, start) : -1;
1756 <span id='Ext-data-Store-method-findRecord'> /**
1757 </span> * Finds the first matching Record in this store by a specific field value.
1758 * @param {String} fieldName The name of the Record field to test.
1759 * @param {String/RegExp} value Either a string that the field value
1760 * should begin with, or a RegExp to test against the field.
1761 * @param {Number} startIndex (optional) The index to start searching at
1762 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1763 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1764 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1765 * @return {Ext.data.Model} The matched record or null
1767 findRecord: function() {
1769 index = me.find.apply(me, arguments);
1770 return index !== -1 ? me.getAt(index) : null;
1773 <span id='Ext-data-Store-method-createFilterFn'> /**
1775 * Returns a filter function used to test a the given property's value. Defers most of the work to
1776 * Ext.util.MixedCollection's createValueMatcher function
1777 * @param {String} property The property to create the filter function for
1778 * @param {String/RegExp} value The string/regex to compare the property value to
1779 * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
1780 * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
1781 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1782 * Ignored if anyMatch is true.
1784 createFilterFn: function(property, value, anyMatch, caseSensitive, exactMatch) {
1785 if (Ext.isEmpty(value)) {
1788 value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
1789 return function(r) {
1790 return value.test(r.data[property]);
1794 <span id='Ext-data-Store-method-findExact'> /**
1795 </span> * Finds the index of the first matching Record in this store by a specific field value.
1796 * @param {String} fieldName The name of the Record field to test.
1797 * @param {Mixed} value The value to match the field against.
1798 * @param {Number} startIndex (optional) The index to start searching at
1799 * @return {Number} The matched index or -1
1801 findExact: function(property, value, start) {
1802 return this.data.findIndexBy(function(rec) {
1803 return rec.get(property) === value;
1808 <span id='Ext-data-Store-method-findBy'> /**
1809 </span> * Find the index of the first matching Record in this Store by a function.
1810 * If the function returns <tt>true</tt> it is considered a match.
1811 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1812 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1813 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1814 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1816 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1817 * @param {Number} startIndex (optional) The index to start searching at
1818 * @return {Number} The matched index or -1
1820 findBy: function(fn, scope, start) {
1821 return this.data.findIndexBy(fn, scope, start);
1824 <span id='Ext-data-Store-method-collect'> /**
1825 </span> * Collects unique values for a particular dataIndex from this store.
1826 * @param {String} dataIndex The property to collect
1827 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1828 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1829 * @return {Array} An array of the unique values
1831 collect: function(dataIndex, allowNull, bypassFilter) {
1833 data = (bypassFilter === true && me.snapshot) ? me.snapshot: me.data;
1835 return data.collect(dataIndex, 'data', allowNull);
1838 <span id='Ext-data-Store-method-getCount'> /**
1839 </span> * Gets the number of cached records.
1840 * <p>If using paging, this may not be the total size of the dataset. If the data object
1841 * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1842 * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
1843 * @return {Number} The number of Records in the Store's cache.
1845 getCount: function() {
1846 return this.data.length || 0;
1849 <span id='Ext-data-Store-method-getTotalCount'> /**
1850 </span> * Returns the total number of {@link Ext.data.Model Model} instances that the {@link Ext.data.proxy.Proxy Proxy}
1851 * indicates exist. This will usually differ from {@link #getCount} when using paging - getCount returns the
1852 * number of records loaded into the Store at the moment, getTotalCount returns the number of records that
1853 * could be loaded into the Store if the Store contained all data
1854 * @return {Number} The total number of Model instances available via the Proxy
1856 getTotalCount: function() {
1857 return this.totalCount;
1860 <span id='Ext-data-Store-method-getAt'> /**
1861 </span> * Get the Record at the specified index.
1862 * @param {Number} index The index of the Record to find.
1863 * @return {Ext.data.Model} The Record at the passed index. Returns undefined if not found.
1865 getAt: function(index) {
1866 return this.data.getAt(index);
1869 <span id='Ext-data-Store-method-getRange'> /**
1870 </span> * Returns a range of Records between specified indices.
1871 * @param {Number} startIndex (optional) The starting index (defaults to 0)
1872 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
1873 * @return {Ext.data.Model[]} An array of Records
1875 getRange: function(start, end) {
1876 return this.data.getRange(start, end);
1879 <span id='Ext-data-Store-method-getById'> /**
1880 </span> * Get the Record with the specified id.
1881 * @param {String} id The id of the Record to find.
1882 * @return {Ext.data.Model} The Record with the passed id. Returns undefined if not found.
1884 getById: function(id) {
1885 return (this.snapshot || this.data).findBy(function(record) {
1886 return record.getId() === id;
1890 <span id='Ext-data-Store-method-indexOf'> /**
1891 </span> * Get the index within the cache of the passed Record.
1892 * @param {Ext.data.Model} record The Ext.data.Model object to find.
1893 * @return {Number} The index of the passed Record. Returns -1 if not found.
1895 indexOf: function(record) {
1896 return this.data.indexOf(record);
1900 <span id='Ext-data-Store-method-indexOfTotal'> /**
1901 </span> * Get the index within the entire dataset. From 0 to the totalCount.
1902 * @param {Ext.data.Model} record The Ext.data.Model object to find.
1903 * @return {Number} The index of the passed Record. Returns -1 if not found.
1905 indexOfTotal: function(record) {
1906 return record.index || this.indexOf(record);
1909 <span id='Ext-data-Store-method-indexOfId'> /**
1910 </span> * Get the index within the cache of the Record with the passed id.
1911 * @param {String} id The id of the Record to find.
1912 * @return {Number} The index of the Record. Returns -1 if not found.
1914 indexOfId: function(id) {
1915 return this.data.indexOfKey(id);
1918 <span id='Ext-data-Store-method-removeAll'> /**
1919 </span> * Remove all items from the store.
1920 * @param {Boolean} silent Prevent the `clear` event from being fired.
1922 removeAll: function(silent) {
1927 me.snapshot.clear();
1929 if (silent !== true) {
1930 me.fireEvent('clear', me);
1935 * Aggregation methods
1938 <span id='Ext-data-Store-method-first'> /**
1939 </span> * Convenience function for getting the first model instance in the store
1940 * @param {Boolean} grouped (Optional) True to perform the operation for each group
1941 * in the store. The value returned will be an object literal with the key being the group
1942 * name and the first record being the value. The grouped parameter is only honored if
1943 * the store has a groupField.
1944 * @return {Ext.data.Model/undefined} The first model instance in the store, or undefined
1946 first: function(grouped) {
1949 if (grouped && me.isGrouped()) {
1950 return me.aggregate(function(records) {
1951 return records.length ? records[0] : undefined;
1954 return me.data.first();
1958 <span id='Ext-data-Store-method-last'> /**
1959 </span> * Convenience function for getting the last model instance in the store
1960 * @param {Boolean} grouped (Optional) True to perform the operation for each group
1961 * in the store. The value returned will be an object literal with the key being the group
1962 * name and the last record being the value. The grouped parameter is only honored if
1963 * the store has a groupField.
1964 * @return {Ext.data.Model/undefined} The last model instance in the store, or undefined
1966 last: function(grouped) {
1969 if (grouped && me.isGrouped()) {
1970 return me.aggregate(function(records) {
1971 var len = records.length;
1972 return len ? records[len - 1] : undefined;
1975 return me.data.last();
1979 <span id='Ext-data-Store-method-sum'> /**
1980 </span> * Sums the value of <tt>property</tt> for each {@link Ext.data.Model record} between <tt>start</tt>
1981 * and <tt>end</tt> and returns the result.
1982 * @param {String} field A field in each record
1983 * @param {Boolean} grouped (Optional) True to perform the operation for each group
1984 * in the store. The value returned will be an object literal with the key being the group
1985 * name and the sum for that group being the value. The grouped parameter is only honored if
1986 * the store has a groupField.
1987 * @return {Number} The sum
1989 sum: function(field, grouped) {
1992 if (grouped && me.isGrouped()) {
1993 return me.aggregate(me.getSum, me, true, [field]);
1995 return me.getSum(me.data.items, field);
1999 // @private, see sum
2000 getSum: function(records, field) {
2003 len = records.length;
2005 for (; i < len; ++i) {
2006 total += records[i].get(field);
2012 <span id='Ext-data-Store-method-count'> /**
2013 </span> * Gets the count of items in the store.
2014 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2015 * in the store. The value returned will be an object literal with the key being the group
2016 * name and the count for each group being the value. The grouped parameter is only honored if
2017 * the store has a groupField.
2018 * @return {Number} the count
2020 count: function(grouped) {
2023 if (grouped && me.isGrouped()) {
2024 return me.aggregate(function(records) {
2025 return records.length;
2028 return me.getCount();
2032 <span id='Ext-data-Store-method-min'> /**
2033 </span> * Gets the minimum value in the store.
2034 * @param {String} field The field in each record
2035 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2036 * in the store. The value returned will be an object literal with the key being the group
2037 * name and the minimum in the group being the value. The grouped parameter is only honored if
2038 * the store has a groupField.
2039 * @return {Mixed/undefined} The minimum value, if no items exist, undefined.
2041 min: function(field, grouped) {
2044 if (grouped && me.isGrouped()) {
2045 return me.aggregate(me.getMin, me, true, [field]);
2047 return me.getMin(me.data.items, field);
2051 // @private, see min
2052 getMin: function(records, field){
2054 len = records.length,
2058 min = records[0].get(field);
2061 for (; i < len; ++i) {
2062 value = records[i].get(field);
2063 if (value < min) {
2070 <span id='Ext-data-Store-method-max'> /**
2071 </span> * Gets the maximum value in the store.
2072 * @param {String} field The field in each record
2073 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2074 * in the store. The value returned will be an object literal with the key being the group
2075 * name and the maximum in the group being the value. The grouped parameter is only honored if
2076 * the store has a groupField.
2077 * @return {Mixed/undefined} The maximum value, if no items exist, undefined.
2079 max: function(field, grouped) {
2082 if (grouped && me.isGrouped()) {
2083 return me.aggregate(me.getMax, me, true, [field]);
2085 return me.getMax(me.data.items, field);
2089 // @private, see max
2090 getMax: function(records, field) {
2092 len = records.length,
2097 max = records[0].get(field);
2100 for (; i < len; ++i) {
2101 value = records[i].get(field);
2102 if (value > max) {
2109 <span id='Ext-data-Store-method-average'> /**
2110 </span> * Gets the average value in the store.
2111 * @param {String} field The field in each record
2112 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2113 * in the store. The value returned will be an object literal with the key being the group
2114 * name and the group average being the value. The grouped parameter is only honored if
2115 * the store has a groupField.
2116 * @return {Mixed/undefined} The average value, if no items exist, 0.
2118 average: function(field, grouped) {
2120 if (grouped && me.isGrouped()) {
2121 return me.aggregate(me.getAverage, me, true, [field]);
2123 return me.getAverage(me.data.items, field);
2127 // @private, see average
2128 getAverage: function(records, field) {
2130 len = records.length,
2133 if (records.length > 0) {
2134 for (; i < len; ++i) {
2135 sum += records[i].get(field);
2142 <span id='Ext-data-Store-method-aggregate'> /**
2143 </span> * Runs the aggregate function for all the records in the store.
2144 * @param {Function} fn The function to execute. The function is called with a single parameter,
2145 * an array of records for that group.
2146 * @param {Object} scope (optional) The scope to execute the function in. Defaults to the store.
2147 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2148 * in the store. The value returned will be an object literal with the key being the group
2149 * name and the group average being the value. The grouped parameter is only honored if
2150 * the store has a groupField.
2151 * @param {Array} args (optional) Any arguments to append to the function call
2152 * @return {Object} An object literal with the group names and their appropriate values.
2154 aggregate: function(fn, scope, grouped, args) {
2156 if (grouped && this.isGrouped()) {
2157 var groups = this.getGroups(),
2159 len = groups.length,
2163 for (; i < len; ++i) {
2165 out[group.name] = fn.apply(scope || this, [group.children].concat(args));
2169 return fn.apply(scope || this, [this.data.items].concat(args));