4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/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 = Ext.create('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>
65 Ext.create('Ext.data.Store', {
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 = Ext.create('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 = Ext.create('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
198 Ext.create('Ext.data.Store', {
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.data.StoreManager', '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. 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 {Object[]/Ext.data.Model[]} data Optional array of Model instances or data objects to load locally. See "Inline data" above for details.
265 <span id='Ext-data-Store-property-groupField'> /**
266 </span> * @property {String} groupField
267 * The field by which to group data in the store. Internally, grouping is very similar to sorting - the
268 * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single
269 * level of grouping, and groups can be fetched via the {@link #getGroups} method.
271 groupField: undefined,
273 <span id='Ext-data-Store-property-groupDir'> /**
274 </span> * The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC"
278 groupDir: "ASC",
280 <span id='Ext-data-Store-cfg-pageSize'> /**
281 </span> * @cfg {Number} pageSize
282 * The number of records considered to form a 'page'. This is used to power the built-in
283 * paging using the nextPage and previousPage functions. Defaults to 25.
287 <span id='Ext-data-Store-property-currentPage'> /**
288 </span> * The page that the Store has most recently loaded (see {@link #loadPage})
289 * @property currentPage
294 <span id='Ext-data-Store-cfg-clearOnPageLoad'> /**
295 </span> * @cfg {Boolean} clearOnPageLoad True to empty the store when loading another page via {@link #loadPage},
296 * {@link #nextPage} or {@link #previousPage}. Setting to false keeps existing records, allowing
297 * large data sets to be loaded one page at a time but rendered all together.
299 clearOnPageLoad: true,
301 <span id='Ext-data-Store-property-loading'> /**
302 </span> * @property {Boolean} loading
303 * True if the Store is currently loading via its Proxy
308 <span id='Ext-data-Store-cfg-sortOnFilter'> /**
309 </span> * @cfg {Boolean} sortOnFilter For local filtering only, causes {@link #sort} to be called whenever {@link #filter} is called,
310 * causing the sorters to be reapplied after filtering. Defaults to true
314 <span id='Ext-data-Store-cfg-buffered'> /**
315 </span> * @cfg {Boolean} buffered
316 * Allow the store to buffer and pre-fetch pages of records. This is to be used in conjunction with a view will
317 * tell the store to pre-fetch records ahead of a time.
321 <span id='Ext-data-Store-cfg-purgePageCount'> /**
322 </span> * @cfg {Number} purgePageCount
323 * The number of pages to keep in the cache before purging additional records. A value of 0 indicates to never purge the prefetched data.
324 * This option is only relevant when the {@link #buffered} option is set to true.
330 onClassExtended: function(cls, data) {
331 var model = data.model;
333 if (typeof model == 'string') {
334 var onBeforeClassCreated = data.onBeforeClassCreated;
336 data.onBeforeClassCreated = function(cls, data) {
339 Ext.require(model, function() {
340 onBeforeClassCreated.call(me, cls, data);
346 <span id='Ext-data-Store-method-constructor'> /**
347 </span> * Creates the store.
348 * @param {Object} config (optional) Config object
350 constructor: function(config) {
351 // Clone the config so we don't modify the original config object
352 config = Ext.Object.merge({}, config);
355 groupers = config.groupers || me.groupers,
356 groupField = config.groupField || me.groupField,
360 if (config.buffered || me.buffered) {
361 me.prefetchData = Ext.create('Ext.util.MixedCollection', false, function(record) {
364 me.pendingRequests = [];
365 me.pagesRequested = [];
367 me.sortOnLoad = false;
368 me.filterOnLoad = false;
372 <span id='Ext-data-Store-event-beforeprefetch'> /**
373 </span> * @event beforeprefetch
374 * Fires before a prefetch occurs. Return false to cancel.
375 * @param {Ext.data.Store} this
376 * @param {Ext.data.Operation} operation The associated operation
379 <span id='Ext-data-Store-event-groupchange'> /**
380 </span> * @event groupchange
381 * Fired whenever the grouping in the grid changes
382 * @param {Ext.data.Store} store The store
383 * @param {Ext.util.Grouper[]} groupers The array of grouper objects
386 <span id='Ext-data-Store-event-load'> /**
387 </span> * @event load
388 * Fires whenever records have been prefetched
389 * @param {Ext.data.Store} this
390 * @param {Ext.util.Grouper[]} records An array of records
391 * @param {Boolean} successful True if the operation was successful.
392 * @param {Ext.data.Operation} operation The associated operation
396 data = config.data || me.data;
398 <span id='Ext-data-Store-property-data'> /**
399 </span> * The MixedCollection that holds this store's local cache of records
401 * @type Ext.util.MixedCollection
403 me.data = Ext.create('Ext.util.MixedCollection', false, function(record) {
404 return record.internalId;
408 me.inlineData = data;
412 if (!groupers && groupField) {
414 property : groupField,
415 direction: config.groupDir || me.groupDir
418 delete config.groupers;
420 <span id='Ext-data-Store-property-groupers'> /**
421 </span> * The collection of {@link Ext.util.Grouper Groupers} currently applied to this Store
423 * @type Ext.util.MixedCollection
425 me.groupers = Ext.create('Ext.util.MixedCollection');
426 me.groupers.addAll(me.decodeGroupers(groupers));
428 this.callParent([config]);
429 // don't use *config* anymore from here on... use *me* instead...
431 if (me.groupers.items.length) {
432 me.sort(me.groupers.items, 'prepend', false);
436 data = me.inlineData;
439 if (proxy instanceof Ext.data.proxy.Memory) {
443 me.add.apply(me, data);
447 delete me.inlineData;
448 } else if (me.autoLoad) {
449 Ext.defer(me.load, 10, me, [typeof me.autoLoad === 'object' ? me.autoLoad: undefined]);
450 // Remove the defer call, we may need reinstate this at some point, but currently it's not obvious why it's here.
451 // this.load(typeof this.autoLoad == 'object' ? this.autoLoad : undefined);
455 onBeforeSort: function() {
456 var groupers = this.groupers;
457 if (groupers.getCount() > 0) {
458 this.sort(groupers.items, 'prepend', false);
462 <span id='Ext-data-Store-method-decodeGroupers'> /**
464 * Normalizes an array of grouper objects, ensuring that they are all Ext.util.Grouper instances
465 * @param {Object[]} groupers The groupers array
466 * @return {Ext.util.Grouper[]} Array of Ext.util.Grouper objects
468 decodeGroupers: function(groupers) {
469 if (!Ext.isArray(groupers)) {
470 if (groupers === undefined) {
473 groupers = [groupers];
477 var length = groupers.length,
478 Grouper = Ext.util.Grouper,
481 for (i = 0; i < length; i++) {
482 config = groupers[i];
484 if (!(config instanceof Grouper)) {
485 if (Ext.isString(config)) {
491 Ext.applyIf(config, {
493 direction: "ASC"
496 //support for 3.x style sorters where a function can be defined as 'fn'
498 config.sorterFn = config.fn;
501 //support a function to be passed as a sorter definition
502 if (typeof config == 'function') {
508 groupers[i] = new Grouper(config);
515 <span id='Ext-data-Store-method-group'> /**
516 </span> * Group data in the store
517 * @param {String/Object[]} groupers Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model},
518 * or an Array of grouper configurations.
519 * @param {String} direction The overall direction to group the data by. Defaults to "ASC".
521 group: function(groupers, direction) {
527 if (Ext.isArray(groupers)) {
528 newGroupers = groupers;
529 } else if (Ext.isObject(groupers)) {
530 newGroupers = [groupers];
531 } else if (Ext.isString(groupers)) {
532 grouper = me.groupers.get(groupers);
539 newGroupers = [grouper];
540 } else if (direction === undefined) {
543 grouper.setDirection(direction);
547 if (newGroupers && newGroupers.length) {
549 newGroupers = me.decodeGroupers(newGroupers);
551 me.groupers.addAll(newGroupers);
554 if (me.remoteGroup) {
557 callback: me.fireGroupChange
560 // need to explicitly force a sort if we have groupers
561 me.sort(null, null, null, hasNew);
562 me.fireGroupChange();
566 <span id='Ext-data-Store-method-clearGrouping'> /**
567 </span> * Clear any groupers in the store
569 clearGrouping: function(){
571 // Clear any groupers we pushed on to the sorters
572 me.groupers.each(function(grouper){
573 me.sorters.remove(grouper);
576 if (me.remoteGroup) {
579 callback: me.fireGroupChange
583 me.fireEvent('groupchange', me, me.groupers);
587 <span id='Ext-data-Store-method-isGrouped'> /**
588 </span> * Checks if the store is currently grouped
589 * @return {Boolean} True if the store is grouped.
591 isGrouped: function() {
592 return this.groupers.getCount() > 0;
595 <span id='Ext-data-Store-method-fireGroupChange'> /**
596 </span> * Fires the groupchange event. Abstracted out so we can use it
600 fireGroupChange: function(){
601 this.fireEvent('groupchange', this, this.groupers);
604 <span id='Ext-data-Store-method-getGroups'> /**
605 </span> * Returns an array containing the result of applying grouping to the records in this store. See {@link #groupField},
606 * {@link #groupDir} and {@link #getGroupString}. Example for a store containing records with a color field:
607 <pre><code>
608 var myStore = Ext.create('Ext.data.Store', {
613 myStore.getGroups(); //returns:
618 //all records where the color field is 'yellow'
624 //all records where the color field is 'red'
628 </code></pre>
629 * @param {String} groupName (Optional) Pass in an optional groupName argument to access a specific group as defined by {@link #getGroupString}
630 * @return {Object/Object[]} The grouped data
632 getGroups: function(requestGroupString) {
633 var records = this.data.items,
634 length = records.length,
642 for (i = 0; i < length; i++) {
644 groupStr = this.getGroupString(record);
645 group = pointers[groupStr];
647 if (group === undefined) {
654 pointers[groupStr] = group;
657 group.children.push(record);
660 return requestGroupString ? pointers[requestGroupString] : groups;
663 <span id='Ext-data-Store-method-getGroupsForGrouper'> /**
665 * For a given set of records and a Grouper, returns an array of arrays - each of which is the set of records
666 * matching a certain group.
668 getGroupsForGrouper: function(records, grouper) {
669 var length = records.length,
677 for (i = 0; i < length; i++) {
679 newValue = grouper.getGroupString(record);
681 if (newValue !== oldValue) {
690 group.records.push(record);
698 <span id='Ext-data-Store-method-getGroupsForGrouperIndex'> /**
700 * This is used recursively to gather the records into the configured Groupers. The data MUST have been sorted for
701 * this to work properly (see {@link #getGroupData} and {@link #getGroupsForGrouper}) Most of the work is done by
702 * {@link #getGroupsForGrouper} - this function largely just handles the recursion.
703 * @param {Ext.data.Model[]} records The set or subset of records to group
704 * @param {Number} grouperIndex The grouper index to retrieve
705 * @return {Object[]} The grouped records
707 getGroupsForGrouperIndex: function(records, grouperIndex) {
709 groupers = me.groupers,
710 grouper = groupers.getAt(grouperIndex),
711 groups = me.getGroupsForGrouper(records, grouper),
712 length = groups.length,
715 if (grouperIndex + 1 < groupers.length) {
716 for (i = 0; i < length; i++) {
717 groups[i].children = me.getGroupsForGrouperIndex(groups[i].records, grouperIndex + 1);
721 for (i = 0; i < length; i++) {
722 groups[i].depth = grouperIndex;
728 <span id='Ext-data-Store-method-getGroupData'> /**
730 * <p>Returns records grouped by the configured {@link #groupers grouper} configuration. Sample return value (in
731 * this case grouping by genre and then author in a fictional books dataset):</p>
732 <pre><code>
738 //book1, book2, book3, book4
758 </code></pre>
759 * @param {Boolean} sort True to call {@link #sort} before finding groups. Sorting is required to make grouping
760 * function correctly so this should only be set to false if the Store is known to already be sorted correctly
762 * @return {Object[]} The group data
764 getGroupData: function(sort) {
766 if (sort !== false) {
770 return me.getGroupsForGrouperIndex(me.data.items, 0);
773 <span id='Ext-data-Store-method-getGroupString'> /**
774 </span> * <p>Returns the string to group on for a given model instance. The default implementation of this method returns
775 * the model's {@link #groupField}, but this can be overridden to group by an arbitrary string. For example, to
776 * group by the first letter of a model's 'name' field, use the following code:</p>
777 <pre><code>
778 Ext.create('Ext.data.Store', {
780 getGroupString: function(instance) {
781 return instance.get('name')[0];
784 </code></pre>
785 * @param {Ext.data.Model} instance The model instance
786 * @return {String} The string to compare when forming groups
788 getGroupString: function(instance) {
789 var group = this.groupers.first();
791 return instance.get(group.property);
795 <span id='Ext-data-Store-method-insert'> /**
796 </span> * Inserts Model instances into the Store at the given index and fires the {@link #add} event.
797 * See also <code>{@link #add}</code>.
798 * @param {Number} index The start index at which to insert the passed Records.
799 * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache.
801 insert: function(index, records) {
808 records = [].concat(records);
809 for (i = 0, len = records.length; i < len; i++) {
810 record = me.createModel(records[i]);
811 record.set(me.modelDefaults);
812 // reassign the model in the array in case it wasn't created yet
815 me.data.insert(index + i, record);
818 sync = sync || record.phantom === true;
822 me.snapshot.addAll(records);
825 me.fireEvent('add', me, records, index);
826 me.fireEvent('datachanged', me);
827 if (me.autoSync && sync) {
832 <span id='Ext-data-Store-method-add'> /**
833 </span> * Adds Model instance to the Store. This method accepts either:
835 * - An array of Model instances or Model configuration objects.
836 * - Any number of Model instance or Model configuration object arguments.
838 * The new Model instances will be added at the end of the existing collection.
842 * myStore.add({some: 'data'}, {some: 'other data'});
844 * @param {Ext.data.Model[]/Ext.data.Model...} model An array of Model instances
845 * or Model configuration objects, or variable number of Model instance or config arguments.
846 * @return {Ext.data.Model[]} The model instances that were added
848 add: function(records) {
849 //accept both a single-argument array of records, or any number of record arguments
850 if (!Ext.isArray(records)) {
851 records = Array.prototype.slice.apply(arguments);
856 length = records.length,
859 for (; i < length; i++) {
860 record = me.createModel(records[i]);
861 // reassign the model in the array in case it wasn't created yet
865 me.insert(me.data.length, records);
870 <span id='Ext-data-Store-method-createModel'> /**
871 </span> * Converts a literal to a model, if it's not a model already
873 * @param record {Ext.data.Model/Object} The record to create
874 * @return {Ext.data.Model}
876 createModel: function(record) {
877 if (!record.isModel) {
878 record = Ext.ModelManager.create(record, this.model);
884 <span id='Ext-data-Store-method-each'> /**
885 </span> * Calls the specified function for each of the {@link Ext.data.Model Records} in the cache.
886 * @param {Function} fn The function to call. The {@link Ext.data.Model Record} is passed as the first parameter.
887 * Returning <tt>false</tt> aborts and exits the iteration.
888 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
889 * Defaults to the current {@link Ext.data.Model Record} in the iteration.
891 each: function(fn, scope) {
892 this.data.each(fn, scope);
895 <span id='Ext-data-Store-method-remove'> /**
896 </span> * Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
897 * 'datachanged' event after removal.
898 * @param {Ext.data.Model/Ext.data.Model[]} records The Ext.data.Model instance or array of instances to remove
900 remove: function(records, /* private */ isMove) {
901 if (!Ext.isArray(records)) {
906 * Pass the isMove parameter if we know we're going to be re-inserting this record
908 isMove = isMove === true;
912 length = records.length,
917 for (; i < length; i++) {
919 index = me.data.indexOf(record);
922 me.snapshot.remove(record);
926 isPhantom = record.phantom === true;
927 if (!isMove && !isPhantom) {
928 // don't push phantom records onto removed
929 me.removed.push(record);
933 me.data.remove(record);
934 sync = sync || !isPhantom;
936 me.fireEvent('remove', me, record, index);
940 me.fireEvent('datachanged', me);
941 if (!isMove && me.autoSync && sync) {
946 <span id='Ext-data-Store-method-removeAt'> /**
947 </span> * Removes the model instance at the given index
948 * @param {Number} index The record index
950 removeAt: function(index) {
951 var record = this.getAt(index);
958 <span id='Ext-data-Store-method-load'> /**
959 </span> * <p>Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an
960 * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved
961 * instances into the Store and calling an optional callback if required. Example usage:</p>
963 <pre><code>
966 callback: function(records, operation, success) {
967 //the {@link Ext.data.Operation operation} object contains all of the details of the load operation
968 console.log(records);
971 </code></pre>
973 * <p>If the callback scope does not need to be set, a function can simply be passed:</p>
975 <pre><code>
976 store.load(function(records, operation, success) {
977 console.log('loaded records');
979 </code></pre>
981 * @param {Object/Function} options (Optional) config object, passed into the Ext.data.Operation object before loading.
983 load: function(options) {
986 options = options || {};
988 if (Ext.isFunction(options)) {
994 Ext.applyIf(options, {
995 groupers: me.groupers.items,
996 page: me.currentPage,
997 start: (me.currentPage - 1) * me.pageSize,
1002 return me.callParent([options]);
1005 <span id='Ext-data-Store-method-onProxyLoad'> /**
1007 * Called internally when a Proxy has completed a load request
1009 onProxyLoad: function(operation) {
1011 resultSet = operation.getResultSet(),
1012 records = operation.getRecords(),
1013 successful = operation.wasSuccessful();
1016 me.totalCount = resultSet.total;
1020 me.loadRecords(records, operation);
1024 me.fireEvent('load', me, records, successful);
1026 //TODO: deprecate this event, it should always have been 'load' instead. 'load' is now documented, 'read' is not.
1027 //People are definitely using this so can't deprecate safely until 2.x
1028 me.fireEvent('read', me, records, operation.wasSuccessful());
1030 //this is a callback that would have been passed to the 'read' function and is optional
1031 Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
1034 <span id='Ext-data-Store-method-onCreateRecords'> /**
1035 </span> * Create any new records when a write is returned from the server.
1037 * @param {Ext.data.Model[]} records The array of new records
1038 * @param {Ext.data.Operation} operation The operation that just completed
1039 * @param {Boolean} success True if the operation was successful
1041 onCreateRecords: function(records, operation, success) {
1045 snapshot = this.snapshot,
1046 length = records.length,
1047 originalRecords = operation.records,
1053 * Loop over each record returned from the server. Assume they are
1054 * returned in order of how they were sent. If we find a matching
1055 * record, replace it with the newly created one.
1057 for (; i < length; ++i) {
1058 record = records[i];
1059 original = originalRecords[i];
1061 index = data.indexOf(original);
1062 if (index > -1) {
1063 data.removeAt(index);
1064 data.insert(index, record);
1067 index = snapshot.indexOf(original);
1068 if (index > -1) {
1069 snapshot.removeAt(index);
1070 snapshot.insert(index, record);
1073 record.phantom = false;
1080 <span id='Ext-data-Store-method-onUpdateRecords'> /**
1081 </span> * Update any records when a write is returned from the server.
1083 * @param {Ext.data.Model[]} records The array of updated records
1084 * @param {Ext.data.Operation} operation The operation that just completed
1085 * @param {Boolean} success True if the operation was successful
1087 onUpdateRecords: function(records, operation, success){
1090 length = records.length,
1092 snapshot = this.snapshot,
1095 for (; i < length; ++i) {
1096 record = records[i];
1097 data.replace(record);
1099 snapshot.replace(record);
1106 <span id='Ext-data-Store-method-onDestroyRecords'> /**
1107 </span> * Remove any records when a write is returned from the server.
1109 * @param {Ext.data.Model[]} records The array of removed records
1110 * @param {Ext.data.Operation} operation The operation that just completed
1111 * @param {Boolean} success True if the operation was successful
1113 onDestroyRecords: function(records, operation, success){
1117 length = records.length,
1119 snapshot = me.snapshot,
1122 for (; i < length; ++i) {
1123 record = records[i];
1125 data.remove(record);
1127 snapshot.remove(record);
1135 getNewRecords: function() {
1136 return this.data.filterBy(this.filterNew).items;
1140 getUpdatedRecords: function() {
1141 return this.data.filterBy(this.filterUpdated).items;
1144 <span id='Ext-data-Store-method-filter'> /**
1145 </span> * Filters the loaded set of records by a given set of filters.
1147 * Filtering by single field:
1149 * store.filter("email", /\.com$/);
1151 * Using multiple filters:
1154 * {property: "email", value: /\.com$/},
1155 * {filterFn: function(item) { return item.get("age") > 10; }}
1158 * Using Ext.util.Filter instances instead of config objects
1159 * (note that we need to specify the {@link Ext.util.Filter#root root} config option in this case):
1162 * Ext.create('Ext.util.Filter', {property: "email", value: /\.com$/, root: 'data'}),
1163 * Ext.create('Ext.util.Filter', {filterFn: function(item) { return item.get("age") > 10; }, root: 'data'})
1166 * @param {Object[]/Ext.util.Filter[]/String} filters The set of filters to apply to the data. These are stored internally on the store,
1167 * but the filtering itself is done on the Store's {@link Ext.util.MixedCollection MixedCollection}. See
1168 * MixedCollection's {@link Ext.util.MixedCollection#filter filter} method for filter syntax. Alternatively,
1169 * pass in a property string
1170 * @param {String} value (optional) value to filter by (only if using a property string as the first argument)
1172 filter: function(filters, value) {
1173 if (Ext.isString(filters)) {
1181 decoded = me.decodeFilters(filters),
1183 doLocalSort = me.sortOnFilter && !me.remoteSort,
1184 length = decoded.length;
1186 for (; i < length; i++) {
1187 me.filters.replace(decoded[i]);
1190 if (me.remoteFilter) {
1191 //the load function will pick up the new filters and request the filtered data from the proxy
1194 <span id='Ext-data-Store-property-snapshot'> /**
1195 </span> * A pristine (unfiltered) collection of the records in this store. This is used to reinstate
1196 * records when a filter is removed or changed
1197 * @property snapshot
1198 * @type Ext.util.MixedCollection
1200 if (me.filters.getCount()) {
1201 me.snapshot = me.snapshot || me.data.clone();
1202 me.data = me.data.filter(me.filters.items);
1207 // fire datachanged event if it hasn't already been fired by doSort
1208 if (!doLocalSort || me.sorters.length < 1) {
1209 me.fireEvent('datachanged', me);
1215 <span id='Ext-data-Store-method-clearFilter'> /**
1216 </span> * Revert to a view of the Record cache with no filtering applied.
1217 * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1218 * {@link #datachanged} event.
1220 clearFilter: function(suppressEvent) {
1225 if (me.remoteFilter) {
1227 } else if (me.isFiltered()) {
1228 me.data = me.snapshot.clone();
1231 if (suppressEvent !== true) {
1232 me.fireEvent('datachanged', me);
1237 <span id='Ext-data-Store-method-isFiltered'> /**
1238 </span> * Returns true if this store is currently filtered
1241 isFiltered: function() {
1242 var snapshot = this.snapshot;
1243 return !! snapshot && snapshot !== this.data;
1246 <span id='Ext-data-Store-method-filterBy'> /**
1247 </span> * Filter by a function. The specified function will be called for each
1248 * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1249 * otherwise it is filtered out.
1250 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1251 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1252 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1253 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1255 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1257 filterBy: function(fn, scope) {
1260 me.snapshot = me.snapshot || me.data.clone();
1261 me.data = me.queryBy(fn, scope || me);
1262 me.fireEvent('datachanged', me);
1265 <span id='Ext-data-Store-method-queryBy'> /**
1266 </span> * Query the cached records in this Store using a filtering function. The specified function
1267 * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1268 * included in the results.
1269 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1270 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1271 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1272 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1274 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1275 * @return {Ext.util.MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1277 queryBy: function(fn, scope) {
1279 data = me.snapshot || me.data;
1280 return data.filterBy(fn, scope || me);
1283 <span id='Ext-data-Store-method-loadData'> /**
1284 </span> * Loads an array of data straight into the Store.
1286 * Using this method is great if the data is in the correct format already (e.g. it doesn't need to be
1287 * processed by a reader). If your data requires processing to decode the data structure, use a
1288 * {@link Ext.data.proxy.Memory MemoryProxy} instead.
1290 * @param {Ext.data.Model[]/Object[]} data Array of data to load. Any non-model instances will be cast
1291 * into model instances.
1292 * @param {Boolean} [append=false] True to add the records to the existing records in the store, false
1293 * to remove the old ones first.
1295 loadData: function(data, append) {
1296 var model = this.model,
1297 length = data.length,
1302 //make sure each data element is an Ext.data.Model instance
1303 for (i = 0; i < length; i++) {
1306 if (!(record instanceof Ext.data.Model)) {
1307 record = Ext.ModelManager.create(record, model);
1309 newData.push(record);
1312 this.loadRecords(newData, {addRecords: append});
1316 <span id='Ext-data-Store-method-loadRawData'> /**
1317 </span> * Loads data via the bound Proxy's reader
1319 * Use this method if you are attempting to load data and want to utilize the configured data reader.
1321 * @param {Object[]} data The full JSON object you'd like to load into the Data store.
1322 * @param {Boolean} [append=false] True to add the records to the existing records in the store, false
1323 * to remove the old ones first.
1325 loadRawData : function(data, append) {
1327 result = me.proxy.reader.read(data),
1328 records = result.records;
1330 if (result.success) {
1331 me.loadRecords(records, { addRecords: append });
1332 me.fireEvent('load', me, records, true);
1337 <span id='Ext-data-Store-method-loadRecords'> /**
1338 </span> * Loads an array of {@link Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually
1339 * be called internally when loading from the {@link Ext.data.proxy.Proxy Proxy}, when adding records manually use {@link #add} instead
1340 * @param {Ext.data.Model[]} records The array of records to load
1341 * @param {Object} options {addRecords: true} to add these records to the existing records, false to remove the Store's existing records first
1343 loadRecords: function(records, options) {
1346 length = records.length;
1348 options = options || {};
1351 if (!options.addRecords) {
1356 me.data.addAll(records);
1358 //FIXME: this is not a good solution. Ed Spencer is totally responsible for this and should be forced to fix it immediately.
1359 for (; i < length; i++) {
1360 if (options.start !== undefined) {
1361 records[i].index = options.start + i;
1364 records[i].join(me);
1368 * this rather inelegant suspension and resumption of events is required because both the filter and sort functions
1369 * fire an additional datachanged event, which is not wanted. Ideally we would do this a different way. The first
1370 * datachanged event is fired by the call to this.add, above.
1374 if (me.filterOnLoad && !me.remoteFilter) {
1378 if (me.sortOnLoad && !me.remoteSort) {
1383 me.fireEvent('datachanged', me, records);
1387 <span id='Ext-data-Store-method-loadPage'> /**
1388 </span> * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal
1389 * load operation, passing in calculated 'start' and 'limit' params
1390 * @param {Number} page The number of the page to load
1391 * @param {Object} options See options for {@link #load}
1393 loadPage: function(page, options) {
1395 options = Ext.apply({}, options);
1397 me.currentPage = page;
1399 me.read(Ext.applyIf(options, {
1401 start: (page - 1) * me.pageSize,
1403 addRecords: !me.clearOnPageLoad
1407 <span id='Ext-data-Store-method-nextPage'> /**
1408 </span> * Loads the next 'page' in the current data set
1409 * @param {Object} options See options for {@link #load}
1411 nextPage: function(options) {
1412 this.loadPage(this.currentPage + 1, options);
1415 <span id='Ext-data-Store-method-previousPage'> /**
1416 </span> * Loads the previous 'page' in the current data set
1417 * @param {Object} options See options for {@link #load}
1419 previousPage: function(options) {
1420 this.loadPage(this.currentPage - 1, options);
1424 clearData: function() {
1426 me.data.each(function(record) {
1434 <span id='Ext-data-Store-method-prefetch'> /**
1435 </span> * Prefetches data into the store using its configured {@link #proxy}.
1436 * @param {Object} options (Optional) config object, passed into the Ext.data.Operation object before loading.
1439 prefetch: function(options) {
1442 requestId = me.getRequestId();
1444 options = options || {};
1446 Ext.applyIf(options, {
1448 filters: me.filters.items,
1449 sorters: me.sorters.items,
1450 requestId: requestId
1452 me.pendingRequests.push(requestId);
1454 operation = Ext.create('Ext.data.Operation', options);
1456 // HACK to implement loadMask support.
1457 //if (operation.blocking) {
1458 // me.fireEvent('beforeload', me, operation);
1460 if (me.fireEvent('beforeprefetch', me, operation) !== false) {
1462 me.proxy.read(operation, me.onProxyPrefetch, me);
1468 <span id='Ext-data-Store-method-prefetchPage'> /**
1469 </span> * Prefetches a page of data.
1470 * @param {Number} page The page to prefetch
1471 * @param {Object} options (Optional) config object, passed into the Ext.data.Operation object before loading.
1474 prefetchPage: function(page, options) {
1476 pageSize = me.pageSize,
1477 start = (page - 1) * me.pageSize,
1478 end = start + pageSize;
1480 // Currently not requesting this page and range isn't already satisified
1481 if (Ext.Array.indexOf(me.pagesRequested, page) === -1 && !me.rangeSatisfied(start, end)) {
1482 options = options || {};
1483 me.pagesRequested.push(page);
1484 Ext.applyIf(options, {
1488 callback: me.onWaitForGuarantee,
1492 me.prefetch(options);
1497 <span id='Ext-data-Store-method-getRequestId'> /**
1498 </span> * Returns a unique requestId to track requests.
1501 getRequestId: function() {
1502 this.requestSeed = this.requestSeed || 1;
1503 return this.requestSeed++;
1506 <span id='Ext-data-Store-method-onProxyPrefetch'> /**
1507 </span> * Called after the configured proxy completes a prefetch operation.
1509 * @param {Ext.data.Operation} operation The operation that completed
1511 onProxyPrefetch: function(operation) {
1513 resultSet = operation.getResultSet(),
1514 records = operation.getRecords(),
1516 successful = operation.wasSuccessful();
1519 me.totalCount = resultSet.total;
1520 me.fireEvent('totalcountchange', me.totalCount);
1524 me.cacheRecords(records, operation);
1526 Ext.Array.remove(me.pendingRequests, operation.requestId);
1527 if (operation.page) {
1528 Ext.Array.remove(me.pagesRequested, operation.page);
1532 me.fireEvent('prefetch', me, records, successful, operation);
1534 // HACK to support loadMask
1535 if (operation.blocking) {
1536 me.fireEvent('load', me, records, successful);
1539 //this is a callback that would have been passed to the 'read' function and is optional
1540 Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
1543 <span id='Ext-data-Store-method-cacheRecords'> /**
1544 </span> * Caches the records in the prefetch and stripes them with their server-side
1547 * @param {Ext.data.Model[]} records The records to cache
1548 * @param {Ext.data.Operation} The associated operation
1550 cacheRecords: function(records, operation) {
1553 length = records.length,
1554 start = operation ? operation.start : 0;
1556 if (!Ext.isDefined(me.totalCount)) {
1557 me.totalCount = records.length;
1558 me.fireEvent('totalcountchange', me.totalCount);
1561 for (; i < length; i++) {
1562 // this is the true index, not the viewIndex
1563 records[i].index = start + i;
1566 me.prefetchData.addAll(records);
1567 if (me.purgePageCount) {
1574 <span id='Ext-data-Store-method-purgeRecords'> /**
1575 </span> * Purge the least recently used records in the prefetch if the purgeCount
1576 * has been exceeded.
1578 purgeRecords: function() {
1580 prefetchCount = me.prefetchData.getCount(),
1581 purgeCount = me.purgePageCount * me.pageSize,
1582 numRecordsToPurge = prefetchCount - purgeCount - 1,
1585 for (; i <= numRecordsToPurge; i++) {
1586 me.prefetchData.removeAt(0);
1590 <span id='Ext-data-Store-method-rangeSatisfied'> /**
1591 </span> * Determines if the range has already been satisfied in the prefetchData.
1593 * @param {Number} start The start index
1594 * @param {Number} end The end index in the range
1596 rangeSatisfied: function(start, end) {
1601 for (; i < end; i++) {
1602 if (!me.prefetchData.getByKey(i)) {
1605 if (end - i > me.pageSize) {
1606 Ext.Error.raise("A single page prefetch could never satisfy this request.");
1615 <span id='Ext-data-Store-method-getPageFromRecordIndex'> /**
1616 </span> * Determines the page from a record index
1617 * @param {Number} index The record index
1618 * @return {Number} The page the record belongs to
1620 getPageFromRecordIndex: function(index) {
1621 return Math.floor(index / this.pageSize) + 1;
1624 <span id='Ext-data-Store-method-onGuaranteedRange'> /**
1625 </span> * Handles a guaranteed range being loaded
1628 onGuaranteedRange: function() {
1630 totalCount = me.getTotalCount(),
1631 start = me.requestStart,
1632 end = ((totalCount - 1) < me.requestEnd) ? totalCount - 1 : me.requestEnd,
1637 end = Math.max(0, end);
1640 if (start > end) {
1643 msg: 'Start (' + start + ') was greater than end (' + end +
1644 ') for the range of records requested (' + me.requestStart + '-' +
1645 me.requestEnd + ')' + (this.storeId ? ' from store "' + this.storeId + '"' : '')
1650 if (start !== me.guaranteedStart && end !== me.guaranteedEnd) {
1651 me.guaranteedStart = start;
1652 me.guaranteedEnd = end;
1654 for (; i <= end; i++) {
1655 record = me.prefetchData.getByKey(i);
1658 // Ext.log('Record with key "' + i + '" was not found and store said it was guaranteed');
1665 me.fireEvent('guaranteedrange', range, start, end);
1667 me.cb.call(me.scope || me, range);
1674 // hack to support loadmask
1677 this.fireEvent('beforeload');
1680 // hack to support loadmask
1681 unmask: function() {
1683 this.fireEvent('load');
1687 <span id='Ext-data-Store-method-hasPendingRequests'> /**
1688 </span> * Returns the number of pending requests out.
1690 hasPendingRequests: function() {
1691 return this.pendingRequests.length;
1695 // wait until all requests finish, until guaranteeing the range.
1696 onWaitForGuarantee: function() {
1697 if (!this.hasPendingRequests()) {
1698 this.onGuaranteedRange();
1702 <span id='Ext-data-Store-method-guaranteeRange'> /**
1703 </span> * Guarantee a specific range, this will load the store with a range (that
1704 * must be the pageSize or smaller) and take care of any loading that may
1707 guaranteeRange: function(start, end, cb, scope) {
1709 if (start && end) {
1710 if (end - start > this.pageSize) {
1714 pageSize: this.pageSize,
1715 msg: "Requested a bigger range than the specified pageSize"
1721 end = (end > this.totalCount) ? this.totalCount - 1 : end;
1725 prefetchData = me.prefetchData,
1727 startLoaded = !!prefetchData.getByKey(start),
1728 endLoaded = !!prefetchData.getByKey(end),
1729 startPage = me.getPageFromRecordIndex(start),
1730 endPage = me.getPageFromRecordIndex(end);
1735 me.requestStart = start;
1736 me.requestEnd = end;
1737 // neither beginning or end are loaded
1738 if (!startLoaded || !endLoaded) {
1739 // same page, lets load it
1740 if (startPage === endPage) {
1742 me.prefetchPage(startPage, {
1744 callback: me.onWaitForGuarantee,
1747 // need to load two pages
1750 me.prefetchPage(startPage, {
1752 callback: me.onWaitForGuarantee,
1755 me.prefetchPage(endPage, {
1757 callback: me.onWaitForGuarantee,
1761 // Request was already satisfied via the prefetch
1763 me.onGuaranteedRange();
1767 // because prefetchData is stored by index
1768 // this invalidates all of the prefetchedData
1771 prefetchData = me.prefetchData,
1778 if (me.remoteSort) {
1779 prefetchData.clear();
1780 me.callParent(arguments);
1782 sorters = me.getSorters();
1783 start = me.guaranteedStart;
1784 end = me.guaranteedEnd;
1786 if (sorters.length) {
1787 prefetchData.sort(sorters);
1788 range = prefetchData.getRange();
1789 prefetchData.clear();
1790 me.cacheRecords(range);
1791 delete me.guaranteedStart;
1792 delete me.guaranteedEnd;
1793 me.guaranteeRange(start, end);
1795 me.callParent(arguments);
1798 me.callParent(arguments);
1802 // overriden to provide striping of the indexes as sorting occurs.
1803 // this cannot be done inside of sort because datachanged has already
1804 // fired and will trigger a repaint of the bound view.
1805 doSort: function(sorterFn) {
1807 if (me.remoteSort) {
1808 //the load function will pick up the new sorters and request the sorted data from the proxy
1811 me.data.sortBy(sorterFn);
1813 var range = me.getRange(),
1816 for (; i < ln; i++) {
1820 me.fireEvent('datachanged', me);
1824 <span id='Ext-data-Store-method-find'> /**
1825 </span> * Finds the index of the first matching Record in this store by a specific field value.
1826 * @param {String} fieldName The name of the Record field to test.
1827 * @param {String/RegExp} value Either a string that the field value
1828 * should begin with, or a RegExp to test against the field.
1829 * @param {Number} startIndex (optional) The index to start searching at
1830 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1831 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1832 * @param {Boolean} exactMatch (optional) True to force exact match (^ and $ characters added to the regex). Defaults to false.
1833 * @return {Number} The matched index or -1
1835 find: function(property, value, start, anyMatch, caseSensitive, exactMatch) {
1836 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
1837 return fn ? this.data.findIndexBy(fn, null, start) : -1;
1840 <span id='Ext-data-Store-method-findRecord'> /**
1841 </span> * Finds the first matching Record in this store by a specific field value.
1842 * @param {String} fieldName The name of the Record field to test.
1843 * @param {String/RegExp} value Either a string that the field value
1844 * should begin with, or a RegExp to test against the field.
1845 * @param {Number} startIndex (optional) The index to start searching at
1846 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1847 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1848 * @param {Boolean} exactMatch (optional) True to force exact match (^ and $ characters added to the regex). Defaults to false.
1849 * @return {Ext.data.Model} The matched record or null
1851 findRecord: function() {
1853 index = me.find.apply(me, arguments);
1854 return index !== -1 ? me.getAt(index) : null;
1857 <span id='Ext-data-Store-method-createFilterFn'> /**
1859 * Returns a filter function used to test a the given property's value. Defers most of the work to
1860 * Ext.util.MixedCollection's createValueMatcher function
1861 * @param {String} property The property to create the filter function for
1862 * @param {String/RegExp} value The string/regex to compare the property value to
1863 * @param {Boolean} [anyMatch=false] True if we don't care if the filter value is not the full value.
1864 * @param {Boolean} [caseSensitive=false] True to create a case-sensitive regex.
1865 * @param {Boolean} [exactMatch=false] True to force exact match (^ and $ characters added to the regex).
1866 * Ignored if anyMatch is true.
1868 createFilterFn: function(property, value, anyMatch, caseSensitive, exactMatch) {
1869 if (Ext.isEmpty(value)) {
1872 value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
1873 return function(r) {
1874 return value.test(r.data[property]);
1878 <span id='Ext-data-Store-method-findExact'> /**
1879 </span> * Finds the index of the first matching Record in this store by a specific field value.
1880 * @param {String} fieldName The name of the Record field to test.
1881 * @param {Object} value The value to match the field against.
1882 * @param {Number} startIndex (optional) The index to start searching at
1883 * @return {Number} The matched index or -1
1885 findExact: function(property, value, start) {
1886 return this.data.findIndexBy(function(rec) {
1887 return rec.get(property) == value;
1892 <span id='Ext-data-Store-method-findBy'> /**
1893 </span> * Find the index of the first matching Record in this Store by a function.
1894 * If the function returns <tt>true</tt> it is considered a match.
1895 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1896 * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1897 * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1898 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1900 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1901 * @param {Number} startIndex (optional) The index to start searching at
1902 * @return {Number} The matched index or -1
1904 findBy: function(fn, scope, start) {
1905 return this.data.findIndexBy(fn, scope, start);
1908 <span id='Ext-data-Store-method-collect'> /**
1909 </span> * Collects unique values for a particular dataIndex from this store.
1910 * @param {String} dataIndex The property to collect
1911 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1912 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1913 * @return {Object[]} An array of the unique values
1915 collect: function(dataIndex, allowNull, bypassFilter) {
1917 data = (bypassFilter === true && me.snapshot) ? me.snapshot: me.data;
1919 return data.collect(dataIndex, 'data', allowNull);
1922 <span id='Ext-data-Store-method-getCount'> /**
1923 </span> * Gets the number of cached records.
1924 * <p>If using paging, this may not be the total size of the dataset. If the data object
1925 * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1926 * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
1927 * @return {Number} The number of Records in the Store's cache.
1929 getCount: function() {
1930 return this.data.length || 0;
1933 <span id='Ext-data-Store-method-getTotalCount'> /**
1934 </span> * Returns the total number of {@link Ext.data.Model Model} instances that the {@link Ext.data.proxy.Proxy Proxy}
1935 * indicates exist. This will usually differ from {@link #getCount} when using paging - getCount returns the
1936 * number of records loaded into the Store at the moment, getTotalCount returns the number of records that
1937 * could be loaded into the Store if the Store contained all data
1938 * @return {Number} The total number of Model instances available via the Proxy
1940 getTotalCount: function() {
1941 return this.totalCount;
1944 <span id='Ext-data-Store-method-getAt'> /**
1945 </span> * Get the Record at the specified index.
1946 * @param {Number} index The index of the Record to find.
1947 * @return {Ext.data.Model} The Record at the passed index. Returns undefined if not found.
1949 getAt: function(index) {
1950 return this.data.getAt(index);
1953 <span id='Ext-data-Store-method-getRange'> /**
1954 </span> * Returns a range of Records between specified indices.
1955 * @param {Number} [startIndex=0] The starting index
1956 * @param {Number} [endIndex] The ending index. Defaults to the last Record in the Store.
1957 * @return {Ext.data.Model[]} An array of Records
1959 getRange: function(start, end) {
1960 return this.data.getRange(start, end);
1963 <span id='Ext-data-Store-method-getById'> /**
1964 </span> * Get the Record with the specified id.
1965 * @param {String} id The id of the Record to find.
1966 * @return {Ext.data.Model} The Record with the passed id. Returns null if not found.
1968 getById: function(id) {
1969 return (this.snapshot || this.data).findBy(function(record) {
1970 return record.getId() === id;
1974 <span id='Ext-data-Store-method-indexOf'> /**
1975 </span> * Get the index within the cache of the passed Record.
1976 * @param {Ext.data.Model} record The Ext.data.Model object to find.
1977 * @return {Number} The index of the passed Record. Returns -1 if not found.
1979 indexOf: function(record) {
1980 return this.data.indexOf(record);
1984 <span id='Ext-data-Store-method-indexOfTotal'> /**
1985 </span> * Get the index within the entire dataset. From 0 to the totalCount.
1986 * @param {Ext.data.Model} record The Ext.data.Model object to find.
1987 * @return {Number} The index of the passed Record. Returns -1 if not found.
1989 indexOfTotal: function(record) {
1990 var index = record.index;
1991 if (index || index === 0) {
1994 return this.indexOf(record);
1997 <span id='Ext-data-Store-method-indexOfId'> /**
1998 </span> * Get the index within the cache of the Record with the passed id.
1999 * @param {String} id The id of the Record to find.
2000 * @return {Number} The index of the Record. Returns -1 if not found.
2002 indexOfId: function(id) {
2003 return this.indexOf(this.getById(id));
2006 <span id='Ext-data-Store-method-removeAll'> /**
2007 </span> * Remove all items from the store.
2008 * @param {Boolean} silent Prevent the `clear` event from being fired.
2010 removeAll: function(silent) {
2015 me.snapshot.clear();
2017 if (silent !== true) {
2018 me.fireEvent('clear', me);
2023 * Aggregation methods
2026 <span id='Ext-data-Store-method-first'> /**
2027 </span> * Convenience function for getting the first model instance in the store
2028 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2029 * in the store. The value returned will be an object literal with the key being the group
2030 * name and the first record being the value. The grouped parameter is only honored if
2031 * the store has a groupField.
2032 * @return {Ext.data.Model/undefined} The first model instance in the store, or undefined
2034 first: function(grouped) {
2037 if (grouped && me.isGrouped()) {
2038 return me.aggregate(function(records) {
2039 return records.length ? records[0] : undefined;
2042 return me.data.first();
2046 <span id='Ext-data-Store-method-last'> /**
2047 </span> * Convenience function for getting the last model instance in the store
2048 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2049 * in the store. The value returned will be an object literal with the key being the group
2050 * name and the last record being the value. The grouped parameter is only honored if
2051 * the store has a groupField.
2052 * @return {Ext.data.Model/undefined} The last model instance in the store, or undefined
2054 last: function(grouped) {
2057 if (grouped && me.isGrouped()) {
2058 return me.aggregate(function(records) {
2059 var len = records.length;
2060 return len ? records[len - 1] : undefined;
2063 return me.data.last();
2067 <span id='Ext-data-Store-method-sum'> /**
2068 </span> * Sums the value of <tt>property</tt> for each {@link Ext.data.Model record} between <tt>start</tt>
2069 * and <tt>end</tt> and returns the result.
2070 * @param {String} field A field in each record
2071 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2072 * in the store. The value returned will be an object literal with the key being the group
2073 * name and the sum for that group being the value. The grouped parameter is only honored if
2074 * the store has a groupField.
2075 * @return {Number} The sum
2077 sum: function(field, grouped) {
2080 if (grouped && me.isGrouped()) {
2081 return me.aggregate(me.getSum, me, true, [field]);
2083 return me.getSum(me.data.items, field);
2087 // @private, see sum
2088 getSum: function(records, field) {
2091 len = records.length;
2093 for (; i < len; ++i) {
2094 total += records[i].get(field);
2100 <span id='Ext-data-Store-method-count'> /**
2101 </span> * Gets the count of items in the store.
2102 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2103 * in the store. The value returned will be an object literal with the key being the group
2104 * name and the count for each group being the value. The grouped parameter is only honored if
2105 * the store has a groupField.
2106 * @return {Number} the count
2108 count: function(grouped) {
2111 if (grouped && me.isGrouped()) {
2112 return me.aggregate(function(records) {
2113 return records.length;
2116 return me.getCount();
2120 <span id='Ext-data-Store-method-min'> /**
2121 </span> * Gets the minimum value in the store.
2122 * @param {String} field The field in each record
2123 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2124 * in the store. The value returned will be an object literal with the key being the group
2125 * name and the minimum in the group being the value. The grouped parameter is only honored if
2126 * the store has a groupField.
2127 * @return {Object} The minimum value, if no items exist, undefined.
2129 min: function(field, grouped) {
2132 if (grouped && me.isGrouped()) {
2133 return me.aggregate(me.getMin, me, true, [field]);
2135 return me.getMin(me.data.items, field);
2139 // @private, see min
2140 getMin: function(records, field){
2142 len = records.length,
2146 min = records[0].get(field);
2149 for (; i < len; ++i) {
2150 value = records[i].get(field);
2151 if (value < min) {
2158 <span id='Ext-data-Store-method-max'> /**
2159 </span> * Gets the maximum value in the store.
2160 * @param {String} field The field in each record
2161 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2162 * in the store. The value returned will be an object literal with the key being the group
2163 * name and the maximum in the group being the value. The grouped parameter is only honored if
2164 * the store has a groupField.
2165 * @return {Object} The maximum value, if no items exist, undefined.
2167 max: function(field, grouped) {
2170 if (grouped && me.isGrouped()) {
2171 return me.aggregate(me.getMax, me, true, [field]);
2173 return me.getMax(me.data.items, field);
2177 // @private, see max
2178 getMax: function(records, field) {
2180 len = records.length,
2185 max = records[0].get(field);
2188 for (; i < len; ++i) {
2189 value = records[i].get(field);
2190 if (value > max) {
2197 <span id='Ext-data-Store-method-average'> /**
2198 </span> * Gets the average value in the store.
2199 * @param {String} field The field in each record
2200 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2201 * in the store. The value returned will be an object literal with the key being the group
2202 * name and the group average being the value. The grouped parameter is only honored if
2203 * the store has a groupField.
2204 * @return {Object} The average value, if no items exist, 0.
2206 average: function(field, grouped) {
2208 if (grouped && me.isGrouped()) {
2209 return me.aggregate(me.getAverage, me, true, [field]);
2211 return me.getAverage(me.data.items, field);
2215 // @private, see average
2216 getAverage: function(records, field) {
2218 len = records.length,
2221 if (records.length > 0) {
2222 for (; i < len; ++i) {
2223 sum += records[i].get(field);
2230 <span id='Ext-data-Store-method-aggregate'> /**
2231 </span> * Runs the aggregate function for all the records in the store.
2232 * @param {Function} fn The function to execute. The function is called with a single parameter,
2233 * an array of records for that group.
2234 * @param {Object} scope (optional) The scope to execute the function in. Defaults to the store.
2235 * @param {Boolean} grouped (Optional) True to perform the operation for each group
2236 * in the store. The value returned will be an object literal with the key being the group
2237 * name and the group average being the value. The grouped parameter is only honored if
2238 * the store has a groupField.
2239 * @param {Array} args (optional) Any arguments to append to the function call
2240 * @return {Object} An object literal with the group names and their appropriate values.
2242 aggregate: function(fn, scope, grouped, args) {
2244 if (grouped && this.isGrouped()) {
2245 var groups = this.getGroups(),
2247 len = groups.length,
2251 for (; i < len; ++i) {
2253 out[group.name] = fn.apply(scope || this, [group.children].concat(args));
2257 return fn.apply(scope || this, [this.data.items].concat(args));
2261 // A dummy empty store with a fieldless Model defined in it.
2262 // Just for binding to Views which are instantiated with no Store defined.
2263 // They will be able to run and render fine, and be bound to a generated Store later.
2264 Ext.regStore('ext-empty-store', {fields: [], proxy: 'proxy'});