3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * @class Ext.data.Store
9 * @extends Ext.util.Observable
10 * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
11 * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
12 * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
13 * <p><u>Retrieving Data</u></p>
14 * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
15 * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
16 * <li>{@link #data} to automatically pass in data</li>
17 * <li>{@link #loadData} to manually pass in data</li>
19 * <p><u>Reading Data</u></p>
20 * <p>A Store object has no inherent knowledge of the format of the data object (it could be
21 * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
22 * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
24 * <p><u>Store Types</u></p>
25 * <p>There are several implementations of Store available which are customized for use with
26 * a specific DataReader implementation. Here is an example using an ArrayStore which implicitly
27 * creates a reader commensurate to an Array data object.</p>
29 var myStore = new Ext.data.ArrayStore({
30 fields: ['fullname', 'first'],
31 idIndex: 0 // id for each record will be the first element
34 * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
36 // create a {@link Ext.data.Record Record} constructor:
37 var rt = Ext.data.Record.create([
41 var myStore = new Ext.data.Store({
42 // explicitly create reader
43 reader: new Ext.data.ArrayReader(
45 idIndex: 0 // id for each record will be the first element
51 * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
54 [1, 'Fred Flintstone', 'Fred'], // note that id for the record is the first element
55 [2, 'Barney Rubble', 'Barney']
57 myStore.loadData(myData);
59 * <p>Records are cached and made available through accessor functions. An example of adding
60 * a record to the store:</p>
63 fullname: 'Full Name',
66 var recId = 100; // provide unique id for the record
67 var r = new myStore.recordType(defaultData, ++recId); // create new record
68 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
70 * <p><u>Writing Data</u></p>
71 * <p>And <b>new in Ext version 3</b>, use the new {@link Ext.data.DataWriter DataWriter} to create an automated, <a href="http://extjs.com/deploy/dev/examples/writer/writer.html">Writable Store</a>
72 * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
74 * Creates a new Store.
75 * @param {Object} config A config object containing the objects needed for the Store to access data,
76 * and read the data into Records.
79 Ext.data.Store = Ext.extend(Ext.util.Observable, {
81 * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
82 * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
86 * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
87 * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
88 * Typically this option, or the <code>{@link #data}</code> option will be specified.
91 * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
92 * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
93 * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
94 * be passed to the store's {@link #load} method.
97 * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
98 * access to a data object. See <code>{@link #url}</code>.
101 * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
102 * Typically this option, or the <code>{@link #url}</code> option will be specified.
105 * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
106 * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
107 * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
110 * @cfg {Ext.data.DataWriter} writer
111 * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
112 * to the server-side database.</p>
113 * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
114 * events on the store are monitored in order to remotely {@link #createRecords create records},
115 * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
116 * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
117 * <br><p>Sample implementation:
119 var writer = new {@link Ext.data.JsonWriter}({
121 writeAllFields: true // write all fields, not just those that changed
124 // Typical Store collecting the Proxy, Reader and Writer together.
125 var store = new Ext.data.Store({
130 writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
132 autoSave: false // <-- false to delay executing create, update, destroy requests
133 // until specifically told to do so.
139 * @cfg {Object} baseParams
140 * <p>An object containing properties which are to be sent as parameters
141 * for <i>every</i> HTTP request.</p>
142 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
143 * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
144 * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
145 * for more details.</p>
146 * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
151 * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
152 * {@link #load} operation. Note that for local sorting, the <tt>direction</tt> property is
153 * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
154 * For example:<pre><code>
157 direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
162 * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
163 * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
164 * in place (defaults to <tt>false</tt>).
165 * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
166 * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
167 * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
168 * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
169 * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
170 * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
176 * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
177 * to is destroyed (defaults to <tt>false</tt>).
178 * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
183 * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
184 * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
185 * for the accessor method to retrieve the modified records.
187 pruneModifiedRecords : false,
190 * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
191 * for the details of what this may contain. This may be useful for accessing any params which were used
192 * to load the current Record cache.
198 * @cfg {Boolean} autoSave
199 * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
200 * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
201 * to send all modifiedRecords to the server.</p>
202 * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
207 * @cfg {Boolean} batch
208 * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
209 * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
210 * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
211 * to <tt>false</tt>.</p>
212 * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
213 * generated for each record.</p>
218 * @cfg {Boolean} restful
219 * Defaults to <tt>false</tt>. Set to <tt>true</tt> to have the Store and the set
220 * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
221 * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
222 * action is described in {@link Ext.data.Api#restActions}. For additional information
223 * see {@link Ext.data.DataProxy#restful}.
224 * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
225 * internally be set to <tt>false</tt>.</p>
230 * @cfg {Object} paramNames
231 * <p>An object containing properties which specify the names of the paging and
232 * sorting parameters passed to remote servers when loading blocks of data. By default, this
233 * object takes the following form:</p><pre><code>
235 start : 'start', // The parameter name which specifies the start row
236 limit : 'limit', // The parameter name which specifies number of rows to return
237 sort : 'sort', // The parameter name which specifies the column to sort on
238 dir : 'dir' // The parameter name which specifies the sort direction
241 * <p>The server must produce the requested data block upon receipt of these parameter names.
242 * If different parameter names are required, this property can be overriden using a configuration
244 * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
245 * the parameter names to use in its {@link #load requests}.
247 paramNames : undefined,
250 * @cfg {Object} defaultParamNames
251 * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
252 * for all stores, this object should be changed on the store prototype.
254 defaultParamNames : {
262 * @property isDestroyed
264 * True if the store has been destroyed already. Read only
269 * @property hasMultiSort
271 * True if this store is currently sorted by more than one field/direction combination.
276 batchKey : '_ext_batch_',
278 constructor : function(config){
279 this.data = new Ext.util.MixedCollection(false);
280 this.data.getKey = function(o){
285 // temporary removed-records cache
288 if(config && config.data){
289 this.inlineData = config.data;
293 Ext.apply(this, config);
296 * See the <code>{@link #baseParams corresponding configuration option}</code>
297 * for a description of this property.
298 * To modify this property see <code>{@link #setBaseParam}</code>.
301 this.baseParams = Ext.isObject(this.baseParams) ? this.baseParams : {};
303 this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
305 if((this.url || this.api) && !this.proxy){
306 this.proxy = new Ext.data.HttpProxy({url: this.url, api: this.api});
308 // If Store is RESTful, so too is the DataProxy
309 if (this.restful === true && this.proxy) {
310 // When operating RESTfully, a unique transaction is generated for each record.
311 // TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
313 Ext.data.Api.restify(this.proxy);
316 if(this.reader){ // reader passed
317 if(!this.recordType){
318 this.recordType = this.reader.recordType;
320 if(this.reader.onMetaChange){
321 this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
323 if (this.writer) { // writer passed
324 if (this.writer instanceof(Ext.data.DataWriter) === false) { // <-- config-object instead of instance.
325 this.writer = this.buildWriter(this.writer);
327 this.writer.meta = this.reader.meta;
328 this.pruneModifiedRecords = true;
333 * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
334 * {@link Ext.data.DataReader Reader}. Read-only.
335 * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
336 * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
337 * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
338 * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
339 // create the data store
340 var store = new Ext.data.ArrayStore({
344 {name: 'price', type: 'float'},
345 {name: 'change', type: 'float'},
346 {name: 'pctChange', type: 'float'},
347 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
350 store.loadData(myData);
353 var grid = new Ext.grid.EditorGridPanel({
355 colModel: new Ext.grid.ColumnModel({
357 {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
358 {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
359 {header: 'Change', renderer: change, dataIndex: 'change'},
360 {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
361 {header: 'Last Updated', width: 85,
362 renderer: Ext.util.Format.dateRenderer('m/d/Y'),
363 dataIndex: 'lastChange'}
370 autoExpandColumn: 'company', // match the id specified in the column model
376 handler : function(){
379 company: 'New Company',
380 lastChange: (new Date()).clearTime(),
384 var recId = 3; // provide unique id
385 var p = new store.recordType(defaultData, recId); // create new record
387 store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
388 grid.startEditing(0, 0);
393 * @property recordType
399 * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
400 * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
402 * @type Ext.util.MixedCollection
404 this.fields = this.recordType.prototype.fields;
411 * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
412 * widget that is using this Store as a Record cache should refresh its view.
413 * @param {Store} this
418 * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
419 * @param {Store} this
420 * @param {Object} meta The JSON metadata
425 * Fires when Records have been {@link #add}ed to the Store
426 * @param {Store} this
427 * @param {Ext.data.Record[]} records The array of Records added
428 * @param {Number} index The index at which the record(s) were added
433 * Fires when a Record has been {@link #remove}d from the Store
434 * @param {Store} this
435 * @param {Ext.data.Record} record The Record that was removed
436 * @param {Number} index The index at which the record was removed
441 * Fires when a Record has been updated
442 * @param {Store} this
443 * @param {Ext.data.Record} record The Record that was updated
444 * @param {String} operation The update operation being performed. Value may be one of:
447 Ext.data.Record.REJECT
448 Ext.data.Record.COMMIT
454 * Fires when the data cache has been cleared.
455 * @param {Store} this
456 * @param {Record[]} The records that were cleared.
461 * <p>Fires if an exception occurs in the Proxy during a remote request.
462 * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
463 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
464 * for additional details.
465 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
471 * Fires before a request is made for a new data object. If the beforeload handler returns
472 * <tt>false</tt> the {@link #load} action will be canceled.
473 * @param {Store} this
474 * @param {Object} options The loading options that were specified (see {@link #load} for details)
479 * Fires after a new set of Records has been loaded.
480 * @param {Store} this
481 * @param {Ext.data.Record[]} records The Records that were loaded
482 * @param {Object} options The loading options that were specified (see {@link #load} for details)
486 * @event loadexception
487 * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
489 * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
490 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
491 * for additional details.
492 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
498 * @param {Ext.data.Store} store
499 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
500 * @param {Record/Record[]} rs The Record(s) being written.
501 * @param {Object} options The loading options that were specified. Edit <code>options.params</code> to add Http parameters to the request. (see {@link #save} for details)
502 * @param {Object} arg The callback's arg object passed to the {@link #request} function
507 * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
508 * Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
509 * a simple 20x response is sufficient for the actions "destroy" and "update". The "create" action should should return 200 along with a database pk).
510 * @param {Ext.data.Store} store
511 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
512 * @param {Object} result The 'data' picked-out out of the response for convenience.
513 * @param {Ext.Direct.Transaction} res
514 * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
519 * Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
520 * @param {Ext.data.Store} store
521 * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
522 * with an array of records for each action.
527 * Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
528 * @param {Ext.data.Store} store
529 * @param {Number} batch The identifier for the batch that was saved.
530 * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
531 * with an array of records for each action.
538 // TODO remove deprecated loadexception with ext-3.0.1
539 this.relayEvents(this.proxy, ['loadexception', 'exception']);
541 // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
545 add: this.createRecords,
546 remove: this.destroyRecord,
547 update: this.updateRecord,
552 this.sortToggle = {};
554 this.setDefaultSort(this.sortField, this.sortDir);
555 }else if(this.sortInfo){
556 this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
559 Ext.data.Store.superclass.constructor.call(this);
562 this.storeId = this.id;
566 Ext.StoreMgr.register(this);
569 this.loadData(this.inlineData);
570 delete this.inlineData;
571 }else if(this.autoLoad){
572 this.load.defer(10, this, [
573 typeof this.autoLoad == 'object' ?
574 this.autoLoad : undefined]);
576 // used internally to uniquely identify a batch
577 this.batchCounter = 0;
582 * builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
583 * @param {Object} config Writer configuration
584 * @return {Ext.data.DataWriter}
587 buildWriter : function(config) {
588 var klass = undefined,
589 type = (config.format || 'json').toLowerCase();
592 klass = Ext.data.JsonWriter;
595 klass = Ext.data.XmlWriter;
598 klass = Ext.data.JsonWriter;
600 return new klass(config);
604 * Destroys the store.
606 destroy : function(){
607 if(!this.isDestroyed){
609 Ext.StoreMgr.unregister(this);
613 Ext.destroy(this.proxy);
614 this.reader = this.writer = null;
615 this.purgeListeners();
616 this.isDestroyed = true;
621 * Add Records to the Store and fires the {@link #add} event. To add Records
622 * to the store from a remote source use <code>{@link #load}({add:true})</code>.
623 * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
624 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
625 * to add to the cache. See {@link #recordType}.
627 add : function(records){
628 records = [].concat(records);
629 if(records.length < 1){
632 for(var i = 0, len = records.length; i < len; i++){
633 records[i].join(this);
635 var index = this.data.length;
636 this.data.addAll(records);
638 this.snapshot.addAll(records);
640 this.fireEvent('add', this, records, index);
644 * (Local sort only) Inserts the passed Record into the Store at the index where it
645 * should go based on the current sort information.
646 * @param {Ext.data.Record} record
648 addSorted : function(record){
649 var index = this.findInsertIndex(record);
650 this.insert(index, record);
654 * Remove Records from the Store and fires the {@link #remove} event.
655 * @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
657 remove : function(record){
658 if(Ext.isArray(record)){
659 Ext.each(record, function(r){
663 var index = this.data.indexOf(record);
666 this.data.removeAt(index);
668 if(this.pruneModifiedRecords){
669 this.modified.remove(record);
672 this.snapshot.remove(record);
675 this.fireEvent('remove', this, record, index);
680 * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
681 * @param {Number} index The index of the record to remove.
683 removeAt : function(index){
684 this.remove(this.getAt(index));
688 * Remove all Records from the Store and fires the {@link #clear} event.
689 * @param {Boolean} silent [false] Defaults to <tt>false</tt>. Set <tt>true</tt> to not fire clear event.
691 removeAll : function(silent){
693 this.each(function(rec){
698 this.snapshot.clear();
700 if(this.pruneModifiedRecords){
703 if (silent !== true) { // <-- prevents write-actions when we just want to clear a store.
704 this.fireEvent('clear', this, items);
709 onClear: function(store, records){
710 Ext.each(records, function(rec, index){
711 this.destroyRecord(this, rec, index);
716 * Inserts Records into the Store at the given index and fires the {@link #add} event.
717 * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
718 * @param {Number} index The start index at which to insert the passed Records.
719 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
721 insert : function(index, records){
722 records = [].concat(records);
723 for(var i = 0, len = records.length; i < len; i++){
724 this.data.insert(index, records[i]);
725 records[i].join(this);
728 this.snapshot.addAll(records);
730 this.fireEvent('add', this, records, index);
734 * Get the index within the cache of the passed Record.
735 * @param {Ext.data.Record} record The Ext.data.Record object to find.
736 * @return {Number} The index of the passed Record. Returns -1 if not found.
738 indexOf : function(record){
739 return this.data.indexOf(record);
743 * Get the index within the cache of the Record with the passed id.
744 * @param {String} id The id of the Record to find.
745 * @return {Number} The index of the Record. Returns -1 if not found.
747 indexOfId : function(id){
748 return this.data.indexOfKey(id);
752 * Get the Record with the specified id.
753 * @param {String} id The id of the Record to find.
754 * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
756 getById : function(id){
757 return (this.snapshot || this.data).key(id);
761 * Get the Record at the specified index.
762 * @param {Number} index The index of the Record to find.
763 * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
765 getAt : function(index){
766 return this.data.itemAt(index);
770 * Returns a range of Records between specified indices.
771 * @param {Number} startIndex (optional) The starting index (defaults to 0)
772 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
773 * @return {Ext.data.Record[]} An array of Records
775 getRange : function(start, end){
776 return this.data.getRange(start, end);
780 storeOptions : function(o){
781 o = Ext.apply({}, o);
784 this.lastOptions = o;
788 clearData: function(){
789 this.data.each(function(rec) {
796 * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
797 * <br><p>Notes:</p><div class="mdetail-params"><ul>
798 * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
799 * loaded. To perform any post-processing where information from the load call is required, specify
800 * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
801 * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
802 * properties in the <code>options.params</code> property to establish the initial position within the
803 * dataset, and the number of Records to cache on each read from the Proxy.</li>
804 * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
805 * will be automatically included with the posted parameters according to the specified
806 * <code>{@link #paramNames}</code>.</li>
808 * @param {Object} options An object containing properties which control loading options:<ul>
809 * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
810 * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
811 * <code>{@link #baseParams}</code> of the same name.</p>
812 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
813 * <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
814 * have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
815 * <li>r : Ext.data.Record[] An Array of Records loaded.</li>
816 * <li>options : Options object from the load call.</li>
817 * <li>success : Boolean success indicator.</li></ul></p></div></li>
818 * <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
819 * to the Store object)</p></div></li>
820 * <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
821 * replace the current cache. <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
823 * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
824 * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
826 load : function(options) {
827 options = Ext.apply({}, options);
828 this.storeOptions(options);
829 if(this.sortInfo && this.remoteSort){
830 var pn = this.paramNames;
831 options.params = Ext.apply({}, options.params);
832 options.params[pn.sort] = this.sortInfo.field;
833 options.params[pn.dir] = this.sortInfo.direction;
836 return this.execute('read', null, options); // <-- null represents rs. No rs for load actions.
838 this.handleException(e);
844 * updateRecord Should not be used directly. This method will be called automatically if a Writer is set.
845 * Listens to 'update' event.
846 * @param {Object} store
847 * @param {Object} record
848 * @param {Object} action
851 updateRecord : function(store, record, action) {
852 if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
858 * Should not be used directly. Store#add will call this automatically if a Writer is set
859 * @param {Object} store
861 * @param {Object} index
864 createRecords : function(store, rs, index) {
865 for (var i = 0, len = rs.length; i < len; i++) {
866 if (rs[i].phantom && rs[i].isValid()) {
867 rs[i].markDirty(); // <-- Mark new records dirty
868 this.modified.push(rs[i]); // <-- add to modified
871 if (this.autoSave === true) {
877 * Destroys a Record. Should not be used directly. It's called by Store#remove if a Writer is set.
878 * @param {Store} store this
879 * @param {Ext.data.Record} record
880 * @param {Number} index
883 destroyRecord : function(store, record, index) {
884 if (this.modified.indexOf(record) != -1) { // <-- handled already if @cfg pruneModifiedRecords == true
885 this.modified.remove(record);
887 if (!record.phantom) {
888 this.removed.push(record);
890 // since the record has already been removed from the store but the server request has not yet been executed,
891 // must keep track of the last known index this record existed. If a server error occurs, the record can be
892 // put back into the store. @see Store#createCallback where the record is returned when response status === false
893 record.lastIndex = index;
895 if (this.autoSave === true) {
902 * This method should generally not be used directly. This method is called internally
903 * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
904 * {@link #remove}, or {@link #update} events fire.
905 * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
906 * @param {Record/Record[]} rs
907 * @param {Object} options
911 execute : function(action, rs, options, /* private */ batch) {
912 // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
913 if (!Ext.data.Api.isAction(action)) {
914 throw new Ext.data.Api.Error('execute', action);
916 // make sure options has a fresh, new params hash
917 options = Ext.applyIf(options||{}, {
920 if(batch !== undefined){
921 this.addToBatch(batch);
923 // have to separate before-events since load has a different signature than create,destroy and save events since load does not
924 // include the rs (record resultset) parameter. Capture return values from the beforeaction into doRequest flag.
925 var doRequest = true;
927 if (action === 'read') {
928 doRequest = this.fireEvent('beforeload', this, options);
929 Ext.applyIf(options.params, this.baseParams);
932 // if Writer is configured as listful, force single-record rs to be [{}] instead of {}
933 // TODO Move listful rendering into DataWriter where the @cfg is defined. Should be easy now.
934 if (this.writer.listful === true && this.restful !== true) {
935 rs = (Ext.isArray(rs)) ? rs : [rs];
937 // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
938 else if (Ext.isArray(rs) && rs.length == 1) {
941 // Write the action to options.params
942 if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
943 this.writer.apply(options.params, this.baseParams, action, rs);
946 if (doRequest !== false) {
947 // Send request to proxy.
948 if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
949 options.params.xaction = action; // <-- really old, probaby unecessary.
951 // Note: Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
952 // We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
953 // the user's configured DataProxy#api
954 // TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
955 // of params. This method is an artifact from Ext2.
956 this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
962 * Saves all pending changes to the store. If the commensurate Ext.data.Api.actions action is not configured, then
963 * the configured <code>{@link #url}</code> will be used.
966 * --------------- --------------------
967 * removed records Ext.data.Api.actions.destroy
968 * phantom records Ext.data.Api.actions.create
969 * {@link #getModifiedRecords modified records} Ext.data.Api.actions.update
971 * @TODO: Create extensions of Error class and send associated Record with thrown exceptions.
972 * e.g.: Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
973 * @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
974 * if there are no items to save or the save was cancelled.
978 throw new Ext.data.Store.Error('writer-undefined');
986 // DESTROY: First check for removed records. Records in this.removed are guaranteed non-phantoms. @see Store#remove
987 if(this.removed.length){
988 queue.push(['destroy', this.removed]);
991 // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
992 var rs = [].concat(this.getModifiedRecords());
994 // CREATE: Next check for phantoms within rs. splice-off and execute create.
996 for(var i = rs.length-1; i >= 0; i--){
997 if(rs[i].phantom === true){
998 var rec = rs.splice(i, 1).shift();
1002 }else if(!rs[i].isValid()){ // <-- while we're here, splice-off any !isValid real records
1006 // If we have valid phantoms, create them...
1007 if(phantoms.length){
1008 queue.push(['create', phantoms]);
1011 // UPDATE: And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
1013 queue.push(['update', rs]);
1018 batch = ++this.batchCounter;
1019 for(var i = 0; i < len; ++i){
1021 data[trans[0]] = trans[1];
1023 if(this.fireEvent('beforesave', this, data) !== false){
1024 for(var i = 0; i < len; ++i){
1026 this.doTransaction(trans[0], trans[1], batch);
1034 // private. Simply wraps call to Store#execute in try/catch. Defers to Store#handleException on error. Loops if batch: false
1035 doTransaction : function(action, rs, batch) {
1036 function transaction(records) {
1038 this.execute(action, records, undefined, batch);
1040 this.handleException(e);
1043 if(this.batch === false){
1044 for(var i = 0, len = rs.length; i < len; i++){
1045 transaction.call(this, rs[i]);
1048 transaction.call(this, rs);
1053 addToBatch : function(batch){
1054 var b = this.batches,
1055 key = this.batchKey + batch,
1068 removeFromBatch : function(batch, action, data){
1069 var b = this.batches,
1070 key = this.batchKey + batch,
1077 arr = o.data[action] || [];
1078 o.data[action] = arr.concat(data);
1082 this.fireEvent('save', this, batch, data);
1089 // @private callback-handler for remote CRUD actions
1090 // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1091 createCallback : function(action, rs, batch) {
1092 var actions = Ext.data.Api.actions;
1093 return (action == 'read') ? this.loadRecords : function(data, response, success) {
1094 // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1095 this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
1096 // If success === false here, exception will have been called in DataProxy
1097 if (success === true) {
1098 this.fireEvent('write', this, action, data, response, rs);
1100 this.removeFromBatch(batch, action, data);
1104 // Clears records from modified array after an exception event.
1105 // NOTE: records are left marked dirty. Do we want to commit them even though they were not updated/realized?
1106 // TODO remove this method?
1107 clearModified : function(rs) {
1108 if (Ext.isArray(rs)) {
1109 for (var n=rs.length-1;n>=0;n--) {
1110 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1113 this.modified.splice(this.modified.indexOf(rs), 1);
1117 // remap record ids in MixedCollection after records have been realized. @see Store#onCreateRecords, @see DataReader#realize
1118 reMap : function(record) {
1119 if (Ext.isArray(record)) {
1120 for (var i = 0, len = record.length; i < len; i++) {
1121 this.reMap(record[i]);
1124 delete this.data.map[record._phid];
1125 this.data.map[record.id] = record;
1126 var index = this.data.keys.indexOf(record._phid);
1127 this.data.keys.splice(index, 1, record.id);
1128 delete record._phid;
1132 // @protected onCreateRecord proxy callback for create action
1133 onCreateRecords : function(success, rs, data) {
1134 if (success === true) {
1136 this.reader.realize(rs, data);
1140 this.handleException(e);
1141 if (Ext.isArray(rs)) {
1142 // Recurse to run back into the try {}. DataReader#realize splices-off the rs until empty.
1143 this.onCreateRecords(success, rs, data);
1149 // @protected, onUpdateRecords proxy callback for update action
1150 onUpdateRecords : function(success, rs, data) {
1151 if (success === true) {
1153 this.reader.update(rs, data);
1155 this.handleException(e);
1156 if (Ext.isArray(rs)) {
1157 // Recurse to run back into the try {}. DataReader#update splices-off the rs until empty.
1158 this.onUpdateRecords(success, rs, data);
1164 // @protected onDestroyRecords proxy callback for destroy action
1165 onDestroyRecords : function(success, rs, data) {
1166 // splice each rec out of this.removed
1167 rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
1168 for (var i=0,len=rs.length;i<len;i++) {
1169 this.removed.splice(this.removed.indexOf(rs[i]), 1);
1171 if (success === false) {
1172 // put records back into store if remote destroy fails.
1173 // @TODO: Might want to let developer decide.
1174 for (i=rs.length-1;i>=0;i--) {
1175 this.insert(rs[i].lastIndex, rs[i]); // <-- lastIndex set in Store#destroyRecord
1180 // protected handleException. Possibly temporary until Ext framework has an exception-handler.
1181 handleException : function(e) {
1182 // @see core/Error.js
1187 * <p>Reloads the Record cache from the configured Proxy using the configured
1188 * {@link Ext.data.Reader Reader} and the options from the last load operation
1190 * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1191 * @param {Object} options <p>(optional) An <tt>Object</tt> containing
1192 * {@link #load loading options} which may override the {@link #lastOptions options}
1193 * used in the last {@link #load} operation. See {@link #load} for details
1194 * (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
1196 * <br><p>To add new params to the existing params:</p><pre><code>
1197 lastOptions = myStore.lastOptions;
1198 Ext.apply(lastOptions.params, {
1201 myStore.reload(lastOptions);
1204 reload : function(options){
1205 this.load(Ext.applyIf(options||{}, this.lastOptions));
1209 // Called as a callback by the Reader during a load operation.
1210 loadRecords : function(o, options, success){
1211 if (this.isDestroyed === true) {
1214 if(!o || success === false){
1215 if(success !== false){
1216 this.fireEvent('load', this, [], options);
1218 if(options.callback){
1219 options.callback.call(options.scope || this, [], options, false, o);
1223 var r = o.records, t = o.totalRecords || r.length;
1224 if(!options || options.add !== true){
1225 if(this.pruneModifiedRecords){
1228 for(var i = 0, len = r.length; i < len; i++){
1232 this.data = this.snapshot;
1233 delete this.snapshot;
1236 this.data.addAll(r);
1237 this.totalLength = t;
1239 this.fireEvent('datachanged', this);
1241 this.totalLength = Math.max(t, this.data.length+r.length);
1244 this.fireEvent('load', this, r, options);
1245 if(options.callback){
1246 options.callback.call(options.scope || this, r, options, true);
1251 * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1252 * which understands the format of the data must have been configured in the constructor.
1253 * @param {Object} data The data block from which to read the Records. The format of the data expected
1254 * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1255 * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1256 * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1257 * the existing cache.
1258 * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1259 * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1260 * new, unique ids will be added.
1262 loadData : function(o, append){
1263 var r = this.reader.readRecords(o);
1264 this.loadRecords(r, {add: append}, true);
1268 * Gets the number of cached records.
1269 * <p>If using paging, this may not be the total size of the dataset. If the data object
1270 * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1271 * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
1272 * @return {Number} The number of Records in the Store's cache.
1274 getCount : function(){
1275 return this.data.length || 0;
1279 * Gets the total number of records in the dataset as returned by the server.
1280 * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1281 * must contain the dataset size. For remote data sources, the value for this property
1282 * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1283 * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1284 * <b>Note</b>: see the Important note in {@link #load}.</p>
1285 * @return {Number} The number of Records as specified in the data object passed to the Reader
1287 * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1289 getTotalCount : function(){
1290 return this.totalLength || 0;
1294 * Returns an object describing the current sort state of this Store.
1295 * @return {Object} The sort state of the Store. An object with two properties:<ul>
1296 * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1297 * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1299 * See <tt>{@link #sortInfo}</tt> for additional details.
1301 getSortState : function(){
1302 return this.sortInfo;
1307 * Invokes sortData if we have sortInfo to sort on and are not sorting remotely
1309 applySort : function(){
1310 if ((this.sortInfo || this.multiSortInfo) && !this.remoteSort) {
1317 * Performs the actual sorting of data. This checks to see if we currently have a multi sort or not. It applies
1318 * each sorter field/direction pair in turn by building an OR'ed master sorting function and running it against
1321 sortData : function() {
1322 var sortInfo = this.hasMultiSort ? this.multiSortInfo : this.sortInfo,
1323 direction = sortInfo.direction || "ASC",
1324 sorters = sortInfo.sorters,
1327 //if we just have a single sorter, pretend it's the first in an array
1328 if (!this.hasMultiSort) {
1329 sorters = [{direction: direction, field: sortInfo.field}];
1332 //create a sorter function for each sorter field/direction combo
1333 for (var i=0, j = sorters.length; i < j; i++) {
1334 sortFns.push(this.createSortFunction(sorters[i].field, sorters[i].direction));
1337 if (sortFns.length == 0) {
1341 //the direction modifier is multiplied with the result of the sorting functions to provide overall sort direction
1342 //(as opposed to direction per field)
1343 var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
1345 //create a function which ORs each sorter together to enable multi-sort
1346 var fn = function(r1, r2) {
1347 var result = sortFns[0].call(this, r1, r2);
1349 //if we have more than one sorter, OR any additional sorter functions together
1350 if (sortFns.length > 1) {
1351 for (var i=1, j = sortFns.length; i < j; i++) {
1352 result = result || sortFns[i].call(this, r1, r2);
1356 return directionModifier * result;
1360 this.data.sort(direction, fn);
1361 if (this.snapshot && this.snapshot != this.data) {
1362 this.snapshot.sort(direction, fn);
1367 * Creates and returns a function which sorts an array by the given field and direction
1368 * @param {String} field The field to create the sorter for
1369 * @param {String} direction The direction to sort by (defaults to "ASC")
1370 * @return {Function} A function which sorts by the field/direction combination provided
1372 createSortFunction: function(field, direction) {
1373 direction = direction || "ASC";
1374 var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
1376 var sortType = this.fields.get(field).sortType;
1378 //create a comparison function. Takes 2 records, returns 1 if record 1 is greater,
1379 //-1 if record 2 is greater or 0 if they are equal
1380 return function(r1, r2) {
1381 var v1 = sortType(r1.data[field]),
1382 v2 = sortType(r2.data[field]);
1384 return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0));
1389 * Sets the default sort column and order to be used by the next {@link #load} operation.
1390 * @param {String} fieldName The name of the field to sort by.
1391 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1393 setDefaultSort : function(field, dir) {
1394 dir = dir ? dir.toUpperCase() : 'ASC';
1395 this.sortInfo = {field: field, direction: dir};
1396 this.sortToggle[field] = dir;
1401 * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1402 * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1403 * This function accepts two call signatures - pass in a field name as the first argument to sort on a single
1404 * field, or pass in an array of sort configuration objects to sort by multiple fields.
1405 * Single sort example:
1406 * store.sort('name', 'ASC');
1407 * Multi sort example:
1418 * In this second form, the sort configs are applied in order, with later sorters sorting within earlier sorters' results.
1419 * For example, if two records with the same name are present they will also be sorted by salary if given the sort configs
1420 * above. Any number of sort configs can be added.
1421 * @param {String/Array} fieldName The name of the field to sort by, or an array of ordered sort configs
1422 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1424 sort : function(fieldName, dir) {
1425 if (Ext.isArray(arguments[0])) {
1426 return this.multiSort.call(this, fieldName, dir);
1428 return this.singleSort(fieldName, dir);
1433 * Sorts the store contents by a single field and direction. This is called internally by {@link sort} and would
1434 * not usually be called manually
1435 * @param {String} fieldName The name of the field to sort by.
1436 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1438 singleSort: function(fieldName, dir) {
1439 var field = this.fields.get(fieldName);
1440 if (!field) return false;
1442 var name = field.name,
1443 sortInfo = this.sortInfo || null,
1444 sortToggle = this.sortToggle ? this.sortToggle[name] : null;
1447 if (sortInfo && sortInfo.field == name) { // toggle sort dir
1448 dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
1450 dir = field.sortDir;
1454 this.sortToggle[name] = dir;
1455 this.sortInfo = {field: name, direction: dir};
1456 this.hasMultiSort = false;
1458 if (this.remoteSort) {
1459 if (!this.load(this.lastOptions)) {
1461 this.sortToggle[name] = sortToggle;
1464 this.sortInfo = sortInfo;
1469 this.fireEvent('datachanged', this);
1474 * Sorts the contents of this store by multiple field/direction sorters. This is called internally by {@link sort}
1475 * and would not usually be called manually.
1476 * Multi sorting only currently applies to local datasets - multiple sort data is not currently sent to a proxy
1477 * if remoteSort is used.
1478 * @param {Array} sorters Array of sorter objects (field and direction)
1479 * @param {String} direction Overall direction to sort the ordered results by (defaults to "ASC")
1481 multiSort: function(sorters, direction) {
1482 this.hasMultiSort = true;
1483 direction = direction || "ASC";
1485 //toggle sort direction
1486 if (this.multiSortInfo && direction == this.multiSortInfo.direction) {
1487 direction = direction.toggle("ASC", "DESC");
1491 * @property multiSortInfo
1493 * Object containing overall sort direction and an ordered array of sorter configs used when sorting on multiple fields
1495 this.multiSortInfo = {
1497 direction: direction
1500 if (this.remoteSort) {
1501 this.singleSort(sorters[0].field, sorters[0].direction);
1505 this.fireEvent('datachanged', this);
1510 * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1511 * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1512 * Returning <tt>false</tt> aborts and exits the iteration.
1513 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
1514 * Defaults to the current {@link Ext.data.Record Record} in the iteration.
1516 each : function(fn, scope){
1517 this.data.each(fn, scope);
1521 * Gets all {@link Ext.data.Record records} modified since the last commit. Modified records are
1522 * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1523 * included. See also <tt>{@link #pruneModifiedRecords}</tt> and
1524 * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1525 * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1526 * modifications. To obtain modified fields within a modified record see
1527 *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1529 getModifiedRecords : function(){
1530 return this.modified;
1534 * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1535 * and <tt>end</tt> and returns the result.
1536 * @param {String} property A field in each record
1537 * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1538 * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1539 * @return {Number} The sum
1541 sum : function(property, start, end){
1542 var rs = this.data.items, v = 0;
1544 end = (end || end === 0) ? end : rs.length-1;
1546 for(var i = start; i <= end; i++){
1547 v += (rs[i].data[property] || 0);
1554 * Returns a filter function used to test a the given property's value. Defers most of the work to
1555 * Ext.util.MixedCollection's createValueMatcher function
1556 * @param {String} property The property to create the filter function for
1557 * @param {String/RegExp} value The string/regex to compare the property value to
1558 * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
1559 * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
1560 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
1562 createFilterFn : function(property, value, anyMatch, caseSensitive, exactMatch){
1563 if(Ext.isEmpty(value, false)){
1566 value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
1567 return function(r) {
1568 return value.test(r.data[property]);
1573 * Given an array of filter functions (each with optional scope), constructs and returns a single function that returns
1574 * the result of all of the filters ANDed together
1575 * @param {Array} filters The array of filter objects (each object should contain an 'fn' and optional scope)
1576 * @return {Function} The multiple filter function
1578 createMultipleFilterFn: function(filters) {
1579 return function(record) {
1582 for (var i=0, j = filters.length; i < j; i++) {
1583 var filter = filters[i],
1585 scope = filter.scope;
1587 isMatch = isMatch && fn.call(scope, record);
1595 * Filter the {@link Ext.data.Record records} by a specified property. Alternatively, pass an array of filter
1596 * options to filter by more than one property.
1597 * Single filter example:
1598 * store.filter('name', 'Ed', true, true); //finds all records containing the substring 'Ed'
1599 * Multiple filter example:
1602 * property : 'name',
1604 * anyMatch : true, //optional, defaults to true
1605 * caseSensitive: true //optional, defaults to true
1608 * //filter functions can also be passed
1610 * fn : function(record) {
1611 * return record.get('age') == 24
1616 * @param {String|Array} field A field on your records, or an array containing multiple filter options
1617 * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1618 * against the field.
1619 * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1620 * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1621 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
1623 filter : function(property, value, anyMatch, caseSensitive, exactMatch){
1624 //we can accept an array of filter objects, or a single filter object - normalize them here
1625 if (Ext.isObject(property)) {
1626 property = [property];
1629 if (Ext.isArray(property)) {
1632 //normalize the filters passed into an array of filter functions
1633 for (var i=0, j = property.length; i < j; i++) {
1634 var filter = property[i],
1636 scope = filter.scope || this;
1638 //if we weren't given a filter function, construct one now
1639 if (!Ext.isFunction(func)) {
1640 func = this.createFilterFn(filter.property, filter.value, filter.anyMatch, filter.caseSensitive, filter.exactMatch);
1643 filters.push({fn: func, scope: scope});
1646 var fn = this.createMultipleFilterFn(filters);
1648 //classic single property filter
1649 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
1652 return fn ? this.filterBy(fn) : this.clearFilter();
1656 * Filter by a function. The specified function will be called for each
1657 * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1658 * otherwise it is filtered out.
1659 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1660 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1661 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1662 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1664 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1666 filterBy : function(fn, scope){
1667 this.snapshot = this.snapshot || this.data;
1668 this.data = this.queryBy(fn, scope||this);
1669 this.fireEvent('datachanged', this);
1673 * Revert to a view of the Record cache with no filtering applied.
1674 * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1675 * {@link #datachanged} event.
1677 clearFilter : function(suppressEvent){
1678 if(this.isFiltered()){
1679 this.data = this.snapshot;
1680 delete this.snapshot;
1681 if(suppressEvent !== true){
1682 this.fireEvent('datachanged', this);
1688 * Returns true if this store is currently filtered
1691 isFiltered : function(){
1692 return !!this.snapshot && this.snapshot != this.data;
1696 * Query the records by a specified property.
1697 * @param {String} field A field on your records
1698 * @param {String/RegExp} value Either a string that the field
1699 * should begin with, or a RegExp to test against the field.
1700 * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
1701 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1702 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1704 query : function(property, value, anyMatch, caseSensitive){
1705 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1706 return fn ? this.queryBy(fn) : this.data.clone();
1710 * Query the cached records in this Store using a filtering function. The specified function
1711 * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1712 * included in the results.
1713 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1714 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1715 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1716 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1718 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1719 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1721 queryBy : function(fn, scope){
1722 var data = this.snapshot || this.data;
1723 return data.filterBy(fn, scope||this);
1727 * Finds the index of the first matching Record in this store by a specific field value.
1728 * @param {String} fieldName The name of the Record field to test.
1729 * @param {String/RegExp} value Either a string that the field value
1730 * should begin with, or a RegExp to test against the field.
1731 * @param {Number} startIndex (optional) The index to start searching at
1732 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1733 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1734 * @return {Number} The matched index or -1
1736 find : function(property, value, start, anyMatch, caseSensitive){
1737 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1738 return fn ? this.data.findIndexBy(fn, null, start) : -1;
1742 * Finds the index of the first matching Record in this store by a specific field value.
1743 * @param {String} fieldName The name of the Record field to test.
1744 * @param {Mixed} value The value to match the field against.
1745 * @param {Number} startIndex (optional) The index to start searching at
1746 * @return {Number} The matched index or -1
1748 findExact: function(property, value, start){
1749 return this.data.findIndexBy(function(rec){
1750 return rec.get(property) === value;
1755 * Find the index of the first matching Record in this Store by a function.
1756 * If the function returns <tt>true</tt> it is considered a match.
1757 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1758 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1759 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1760 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1762 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1763 * @param {Number} startIndex (optional) The index to start searching at
1764 * @return {Number} The matched index or -1
1766 findBy : function(fn, scope, start){
1767 return this.data.findIndexBy(fn, scope, start);
1771 * Collects unique values for a particular dataIndex from this store.
1772 * @param {String} dataIndex The property to collect
1773 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1774 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1775 * @return {Array} An array of the unique values
1777 collect : function(dataIndex, allowNull, bypassFilter){
1778 var d = (bypassFilter === true && this.snapshot) ?
1779 this.snapshot.items : this.data.items;
1780 var v, sv, r = [], l = {};
1781 for(var i = 0, len = d.length; i < len; i++){
1782 v = d[i].data[dataIndex];
1784 if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
1793 afterEdit : function(record){
1794 if(this.modified.indexOf(record) == -1){
1795 this.modified.push(record);
1797 this.fireEvent('update', this, record, Ext.data.Record.EDIT);
1801 afterReject : function(record){
1802 this.modified.remove(record);
1803 this.fireEvent('update', this, record, Ext.data.Record.REJECT);
1807 afterCommit : function(record){
1808 this.modified.remove(record);
1809 this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
1813 * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
1814 * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
1815 * Ext.data.Record.COMMIT.
1817 commitChanges : function(){
1818 var m = this.modified.slice(0);
1820 for(var i = 0, len = m.length; i < len; i++){
1826 * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
1828 rejectChanges : function(){
1829 var m = this.modified.slice(0);
1831 for(var i = 0, len = m.length; i < len; i++){
1834 var m = this.removed.slice(0).reverse();
1836 for(var i = 0, len = m.length; i < len; i++){
1837 this.insert(m[i].lastIndex||0, m[i]);
1843 onMetaChange : function(meta){
1844 this.recordType = this.reader.recordType;
1845 this.fields = this.recordType.prototype.fields;
1846 delete this.snapshot;
1847 if(this.reader.meta.sortInfo){
1848 this.sortInfo = this.reader.meta.sortInfo;
1849 }else if(this.sortInfo && !this.fields.get(this.sortInfo.field)){
1850 delete this.sortInfo;
1853 this.writer.meta = this.reader.meta;
1856 this.fireEvent('metachange', this, this.reader.meta);
1860 findInsertIndex : function(record){
1861 this.suspendEvents();
1862 var data = this.data.clone();
1863 this.data.add(record);
1865 var index = this.data.indexOf(record);
1867 this.resumeEvents();
1872 * Set the value for a property name in this store's {@link #baseParams}. Usage:</p><pre><code>
1873 myStore.setBaseParam('foo', {bar:3});
1875 * @param {String} name Name of the property to assign
1876 * @param {Mixed} value Value to assign the <tt>name</tt>d property
1878 setBaseParam : function (name, value){
1879 this.baseParams = this.baseParams || {};
1880 this.baseParams[name] = value;
1884 Ext.reg('store', Ext.data.Store);
1887 * @class Ext.data.Store.Error
1888 * @extends Ext.Error
1889 * Store Error extension.
1890 * @param {String} name
1892 Ext.data.Store.Error = Ext.extend(Ext.Error, {
1893 name: 'Ext.data.Store'
1895 Ext.apply(Ext.data.Store.Error.prototype, {
1897 'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'