3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
4 <title>The source code</title>
5 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
6 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
8 <body onload="prettyPrint();">
9 <pre class="prettyprint lang-js">/*!
10 * Ext JS Library 3.2.2
11 * Copyright(c) 2006-2010 Ext JS, Inc.
13 * http://www.extjs.com/license
15 <div id="cls-Ext.data.Store"></div>/**
16 * @class Ext.data.Store
17 * @extends Ext.util.Observable
18 * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
19 * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
20 * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
21 * <p><u>Retrieving Data</u></p>
22 * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
23 * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
24 * <li>{@link #data} to automatically pass in data</li>
25 * <li>{@link #loadData} to manually pass in data</li>
27 * <p><u>Reading Data</u></p>
28 * <p>A Store object has no inherent knowledge of the format of the data object (it could be
29 * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
30 * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
32 * <p><u>Store Types</u></p>
33 * <p>There are several implementations of Store available which are customized for use with
34 * a specific DataReader implementation. Here is an example using an ArrayStore which implicitly
35 * creates a reader commensurate to an Array data object.</p>
37 var myStore = new Ext.data.ArrayStore({
38 fields: ['fullname', 'first'],
39 idIndex: 0 // id for each record will be the first element
42 * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
44 // create a {@link Ext.data.Record Record} constructor:
45 var rt = Ext.data.Record.create([
49 var myStore = new Ext.data.Store({
50 // explicitly create reader
51 reader: new Ext.data.ArrayReader(
53 idIndex: 0 // id for each record will be the first element
59 * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
62 [1, 'Fred Flintstone', 'Fred'], // note that id for the record is the first element
63 [2, 'Barney Rubble', 'Barney']
65 myStore.loadData(myData);
67 * <p>Records are cached and made available through accessor functions. An example of adding
68 * a record to the store:</p>
71 fullname: 'Full Name',
74 var recId = 100; // provide unique id for the record
75 var r = new myStore.recordType(defaultData, ++recId); // create new record
76 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
78 * <p><u>Writing Data</u></p>
79 * <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>
80 * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
82 * Creates a new Store.
83 * @param {Object} config A config object containing the objects needed for the Store to access data,
84 * and read the data into Records.
87 Ext.data.Store = Ext.extend(Ext.util.Observable, {
88 <div id="cfg-Ext.data.Store-storeId"></div>/**
89 * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
90 * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
93 <div id="cfg-Ext.data.Store-url"></div>/**
94 * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
95 * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
96 * Typically this option, or the <code>{@link #data}</code> option will be specified.
98 <div id="cfg-Ext.data.Store-autoLoad"></div>/**
99 * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
100 * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
101 * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
102 * be passed to the store's {@link #load} method.
104 <div id="cfg-Ext.data.Store-proxy"></div>/**
105 * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
106 * access to a data object. See <code>{@link #url}</code>.
108 <div id="cfg-Ext.data.Store-data"></div>/**
109 * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
110 * Typically this option, or the <code>{@link #url}</code> option will be specified.
112 <div id="cfg-Ext.data.Store-reader"></div>/**
113 * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
114 * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
115 * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
117 <div id="cfg-Ext.data.Store-writer"></div>/**
118 * @cfg {Ext.data.DataWriter} writer
119 * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
120 * to the server-side database.</p>
121 * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
122 * events on the store are monitored in order to remotely {@link #createRecords create records},
123 * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
124 * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
125 * <br><p>Sample implementation:
127 var writer = new {@link Ext.data.JsonWriter}({
129 writeAllFields: true // write all fields, not just those that changed
132 // Typical Store collecting the Proxy, Reader and Writer together.
133 var store = new Ext.data.Store({
138 writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
140 autoSave: false // <-- false to delay executing create, update, destroy requests
141 // until specifically told to do so.
146 <div id="cfg-Ext.data.Store-baseParams"></div>/**
147 * @cfg {Object} baseParams
148 * <p>An object containing properties which are to be sent as parameters
149 * for <i>every</i> HTTP request.</p>
150 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
151 * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
152 * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
153 * for more details.</p>
154 * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
158 <div id="cfg-Ext.data.Store-sortInfo"></div>/**
159 * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
160 * {@link #load} operation. Note that for local sorting, the <tt>direction</tt> property is
161 * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
162 * For example:<pre><code>
165 direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
169 <div id="cfg-Ext.data.Store-remoteSort"></div>/**
170 * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
171 * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
172 * in place (defaults to <tt>false</tt>).
173 * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
174 * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
175 * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
176 * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
177 * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
178 * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
183 <div id="cfg-Ext.data.Store-autoDestroy"></div>/**
184 * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
185 * to is destroyed (defaults to <tt>false</tt>).
186 * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
190 <div id="cfg-Ext.data.Store-pruneModifiedRecords"></div>/**
191 * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
192 * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
193 * for the accessor method to retrieve the modified records.
195 pruneModifiedRecords : false,
197 <div id="prop-Ext.data.Store-lastOptions"></div>/**
198 * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
199 * for the details of what this may contain. This may be useful for accessing any params which were used
200 * to load the current Record cache.
205 <div id="cfg-Ext.data.Store-autoSave"></div>/**
206 * @cfg {Boolean} autoSave
207 * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
208 * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
209 * to send all modifiedRecords to the server.</p>
210 * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
214 <div id="cfg-Ext.data.Store-batch"></div>/**
215 * @cfg {Boolean} batch
216 * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
217 * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
218 * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
219 * to <tt>false</tt>.</p>
220 * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
221 * generated for each record.</p>
225 <div id="cfg-Ext.data.Store-restful"></div>/**
226 * @cfg {Boolean} restful
227 * Defaults to <tt>false</tt>. Set to <tt>true</tt> to have the Store and the set
228 * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
229 * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
230 * action is described in {@link Ext.data.Api#restActions}. For additional information
231 * see {@link Ext.data.DataProxy#restful}.
232 * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
233 * internally be set to <tt>false</tt>.</p>
237 <div id="cfg-Ext.data.Store-paramNames"></div>/**
238 * @cfg {Object} paramNames
239 * <p>An object containing properties which specify the names of the paging and
240 * sorting parameters passed to remote servers when loading blocks of data. By default, this
241 * object takes the following form:</p><pre><code>
243 start : 'start', // The parameter name which specifies the start row
244 limit : 'limit', // The parameter name which specifies number of rows to return
245 sort : 'sort', // The parameter name which specifies the column to sort on
246 dir : 'dir' // The parameter name which specifies the sort direction
249 * <p>The server must produce the requested data block upon receipt of these parameter names.
250 * If different parameter names are required, this property can be overriden using a configuration
252 * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
253 * the parameter names to use in its {@link #load requests}.
255 paramNames : undefined,
257 <div id="cfg-Ext.data.Store-defaultParamNames"></div>/**
258 * @cfg {Object} defaultParamNames
259 * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
260 * for all stores, this object should be changed on the store prototype.
262 defaultParamNames : {
269 <div id="prop-Ext.data.Store-{Boolean}"></div>/**
270 * @property {Boolean} isDestroyed
271 * True if the store has been destroyed already. Read only
275 <div id="prop-Ext.data.Store-{Boolean}"></div>/**
276 * @property {Boolean} hasMultiSort
277 * True if this store is currently sorted by more than one field/direction combination.
282 batchKey : '_ext_batch_',
284 constructor : function(config){
285 this.data = new Ext.util.MixedCollection(false);
286 this.data.getKey = function(o){
291 // temporary removed-records cache
294 if(config && config.data){
295 this.inlineData = config.data;
299 Ext.apply(this, config);
301 <div id="prop-Ext.data.Store-baseParams"></div>/**
302 * See the <code>{@link #baseParams corresponding configuration option}</code>
303 * for a description of this property.
304 * To modify this property see <code>{@link #setBaseParam}</code>.
307 this.baseParams = Ext.isObject(this.baseParams) ? this.baseParams : {};
309 this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
311 if((this.url || this.api) && !this.proxy){
312 this.proxy = new Ext.data.HttpProxy({url: this.url, api: this.api});
314 // If Store is RESTful, so too is the DataProxy
315 if (this.restful === true && this.proxy) {
316 // When operating RESTfully, a unique transaction is generated for each record.
317 // TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
319 Ext.data.Api.restify(this.proxy);
322 if(this.reader){ // reader passed
323 if(!this.recordType){
324 this.recordType = this.reader.recordType;
326 if(this.reader.onMetaChange){
327 this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
329 if (this.writer) { // writer passed
330 if (this.writer instanceof(Ext.data.DataWriter) === false) { // <-- config-object instead of instance.
331 this.writer = this.buildWriter(this.writer);
333 this.writer.meta = this.reader.meta;
334 this.pruneModifiedRecords = true;
338 <div id="prop-Ext.data.Store-recordType"></div>/**
339 * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
340 * {@link Ext.data.DataReader Reader}. Read-only.
341 * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
342 * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
343 * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
344 * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
345 // create the data store
346 var store = new Ext.data.ArrayStore({
350 {name: 'price', type: 'float'},
351 {name: 'change', type: 'float'},
352 {name: 'pctChange', type: 'float'},
353 {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
356 store.loadData(myData);
359 var grid = new Ext.grid.EditorGridPanel({
361 colModel: new Ext.grid.ColumnModel({
363 {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
364 {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
365 {header: 'Change', renderer: change, dataIndex: 'change'},
366 {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
367 {header: 'Last Updated', width: 85,
368 renderer: Ext.util.Format.dateRenderer('m/d/Y'),
369 dataIndex: 'lastChange'}
376 autoExpandColumn: 'company', // match the id specified in the column model
382 handler : function(){
385 company: 'New Company',
386 lastChange: (new Date()).clearTime(),
390 var recId = 3; // provide unique id
391 var p = new store.recordType(defaultData, recId); // create new record
393 store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
394 grid.startEditing(0, 0);
399 * @property recordType
404 <div id="prop-Ext.data.Store-fields"></div>/**
405 * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
406 * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
408 * @type Ext.util.MixedCollection
410 this.fields = this.recordType.prototype.fields;
415 <div id="event-Ext.data.Store-datachanged"></div>/**
417 * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
418 * widget that is using this Store as a Record cache should refresh its view.
419 * @param {Store} this
422 <div id="event-Ext.data.Store-metachange"></div>/**
424 * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
425 * @param {Store} this
426 * @param {Object} meta The JSON metadata
429 <div id="event-Ext.data.Store-add"></div>/**
431 * Fires when Records have been {@link #add}ed to the Store
432 * @param {Store} this
433 * @param {Ext.data.Record[]} records The array of Records added
434 * @param {Number} index The index at which the record(s) were added
437 <div id="event-Ext.data.Store-remove"></div>/**
439 * Fires when a Record has been {@link #remove}d from the Store
440 * @param {Store} this
441 * @param {Ext.data.Record} record The Record that was removed
442 * @param {Number} index The index at which the record was removed
445 <div id="event-Ext.data.Store-update"></div>/**
447 * Fires when a Record has been updated
448 * @param {Store} this
449 * @param {Ext.data.Record} record The Record that was updated
450 * @param {String} operation The update operation being performed. Value may be one of:
453 Ext.data.Record.REJECT
454 Ext.data.Record.COMMIT
458 <div id="event-Ext.data.Store-clear"></div>/**
460 * Fires when the data cache has been cleared.
461 * @param {Store} this
462 * @param {Record[]} records The records that were cleared.
465 <div id="event-Ext.data.Store-exception"></div>/**
467 * <p>Fires if an exception occurs in the Proxy during a remote request.
468 * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
469 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
470 * for additional details.
471 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
475 <div id="event-Ext.data.Store-beforeload"></div>/**
477 * Fires before a request is made for a new data object. If the beforeload handler returns
478 * <tt>false</tt> the {@link #load} action will be canceled.
479 * @param {Store} this
480 * @param {Object} options The loading options that were specified (see {@link #load} for details)
483 <div id="event-Ext.data.Store-load"></div>/**
485 * Fires after a new set of Records has been loaded.
486 * @param {Store} this
487 * @param {Ext.data.Record[]} records The Records that were loaded
488 * @param {Object} options The loading options that were specified (see {@link #load} for details)
491 <div id="event-Ext.data.Store-loadexception"></div>/**
492 * @event loadexception
493 * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
495 * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
496 * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
497 * for additional details.
498 * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
502 <div id="event-Ext.data.Store-beforewrite"></div>/**
504 * @param {Ext.data.Store} store
505 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
506 * @param {Record/Record[]} rs The Record(s) being written.
507 * @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)
508 * @param {Object} arg The callback's arg object passed to the {@link #request} function
511 <div id="event-Ext.data.Store-write"></div>/**
513 * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
514 * Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
515 * a simple 20x response is sufficient for the actions "destroy" and "update". The "create" action should should return 200 along with a database pk).
516 * @param {Ext.data.Store} store
517 * @param {String} action [Ext.data.Api.actions.create|update|destroy]
518 * @param {Object} result The 'data' picked-out out of the response for convenience.
519 * @param {Ext.Direct.Transaction} res
520 * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
523 <div id="event-Ext.data.Store-beforesave"></div>/**
525 * Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
526 * @param {Ext.data.Store} store
527 * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
528 * with an array of records for each action.
531 <div id="event-Ext.data.Store-save"></div>/**
533 * Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
534 * @param {Ext.data.Store} store
535 * @param {Number} batch The identifier for the batch that was saved.
536 * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
537 * with an array of records for each action.
544 // TODO remove deprecated loadexception with ext-3.0.1
545 this.relayEvents(this.proxy, ['loadexception', 'exception']);
547 // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
551 add: this.createRecords,
552 remove: this.destroyRecord,
553 update: this.updateRecord,
558 this.sortToggle = {};
560 this.setDefaultSort(this.sortField, this.sortDir);
561 }else if(this.sortInfo){
562 this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
565 Ext.data.Store.superclass.constructor.call(this);
568 this.storeId = this.id;
572 Ext.StoreMgr.register(this);
575 this.loadData(this.inlineData);
576 delete this.inlineData;
577 }else if(this.autoLoad){
578 this.load.defer(10, this, [
579 typeof this.autoLoad == 'object' ?
580 this.autoLoad : undefined]);
582 // used internally to uniquely identify a batch
583 this.batchCounter = 0;
588 * builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
589 * @param {Object} config Writer configuration
590 * @return {Ext.data.DataWriter}
593 buildWriter : function(config) {
594 var klass = undefined,
595 type = (config.format || 'json').toLowerCase();
598 klass = Ext.data.JsonWriter;
601 klass = Ext.data.XmlWriter;
604 klass = Ext.data.JsonWriter;
606 return new klass(config);
609 <div id="method-Ext.data.Store-destroy"></div>/**
610 * Destroys the store.
612 destroy : function(){
613 if(!this.isDestroyed){
615 Ext.StoreMgr.unregister(this);
619 Ext.destroy(this.proxy);
620 this.reader = this.writer = null;
621 this.purgeListeners();
622 this.isDestroyed = true;
626 <div id="method-Ext.data.Store-add"></div>/**
627 * Add Records to the Store and fires the {@link #add} event. To add Records
628 * to the store from a remote source use <code>{@link #load}({add:true})</code>.
629 * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
630 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
631 * to add to the cache. See {@link #recordType}.
633 add : function(records){
634 records = [].concat(records);
635 if(records.length < 1){
638 for(var i = 0, len = records.length; i < len; i++){
639 records[i].join(this);
641 var index = this.data.length;
642 this.data.addAll(records);
644 this.snapshot.addAll(records);
646 this.fireEvent('add', this, records, index);
649 <div id="method-Ext.data.Store-addSorted"></div>/**
650 * (Local sort only) Inserts the passed Record into the Store at the index where it
651 * should go based on the current sort information.
652 * @param {Ext.data.Record} record
654 addSorted : function(record){
655 var index = this.findInsertIndex(record);
656 this.insert(index, record);
659 <div id="method-Ext.data.Store-remove"></div>/**
660 * Remove Records from the Store and fires the {@link #remove} event.
661 * @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
663 remove : function(record){
664 if(Ext.isArray(record)){
665 Ext.each(record, function(r){
670 var index = this.data.indexOf(record);
673 this.data.removeAt(index);
675 if(this.pruneModifiedRecords){
676 this.modified.remove(record);
679 this.snapshot.remove(record);
682 this.fireEvent('remove', this, record, index);
686 <div id="method-Ext.data.Store-removeAt"></div>/**
687 * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
688 * @param {Number} index The index of the record to remove.
690 removeAt : function(index){
691 this.remove(this.getAt(index));
694 <div id="method-Ext.data.Store-removeAll"></div>/**
695 * Remove all Records from the Store and fires the {@link #clear} event.
696 * @param {Boolean} silent [false] Defaults to <tt>false</tt>. Set <tt>true</tt> to not fire clear event.
698 removeAll : function(silent){
700 this.each(function(rec){
705 this.snapshot.clear();
707 if(this.pruneModifiedRecords){
710 if (silent !== true) { // <-- prevents write-actions when we just want to clear a store.
711 this.fireEvent('clear', this, items);
716 onClear: function(store, records){
717 Ext.each(records, function(rec, index){
718 this.destroyRecord(this, rec, index);
722 <div id="method-Ext.data.Store-insert"></div>/**
723 * Inserts Records into the Store at the given index and fires the {@link #add} event.
724 * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
725 * @param {Number} index The start index at which to insert the passed Records.
726 * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
728 insert : function(index, records){
729 records = [].concat(records);
730 for(var i = 0, len = records.length; i < len; i++){
731 this.data.insert(index, records[i]);
732 records[i].join(this);
735 this.snapshot.addAll(records);
737 this.fireEvent('add', this, records, index);
740 <div id="method-Ext.data.Store-indexOf"></div>/**
741 * Get the index within the cache of the passed Record.
742 * @param {Ext.data.Record} record The Ext.data.Record object to find.
743 * @return {Number} The index of the passed Record. Returns -1 if not found.
745 indexOf : function(record){
746 return this.data.indexOf(record);
749 <div id="method-Ext.data.Store-indexOfId"></div>/**
750 * Get the index within the cache of the Record with the passed id.
751 * @param {String} id The id of the Record to find.
752 * @return {Number} The index of the Record. Returns -1 if not found.
754 indexOfId : function(id){
755 return this.data.indexOfKey(id);
758 <div id="method-Ext.data.Store-getById"></div>/**
759 * Get the Record with the specified id.
760 * @param {String} id The id of the Record to find.
761 * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
763 getById : function(id){
764 return (this.snapshot || this.data).key(id);
767 <div id="method-Ext.data.Store-getAt"></div>/**
768 * Get the Record at the specified index.
769 * @param {Number} index The index of the Record to find.
770 * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
772 getAt : function(index){
773 return this.data.itemAt(index);
776 <div id="method-Ext.data.Store-getRange"></div>/**
777 * Returns a range of Records between specified indices.
778 * @param {Number} startIndex (optional) The starting index (defaults to 0)
779 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
780 * @return {Ext.data.Record[]} An array of Records
782 getRange : function(start, end){
783 return this.data.getRange(start, end);
787 storeOptions : function(o){
788 o = Ext.apply({}, o);
791 this.lastOptions = o;
795 clearData: function(){
796 this.data.each(function(rec) {
802 <div id="method-Ext.data.Store-load"></div>/**
803 * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
804 * <br><p>Notes:</p><div class="mdetail-params"><ul>
805 * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
806 * loaded. To perform any post-processing where information from the load call is required, specify
807 * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
808 * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
809 * properties in the <code>options.params</code> property to establish the initial position within the
810 * dataset, and the number of Records to cache on each read from the Proxy.</li>
811 * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
812 * will be automatically included with the posted parameters according to the specified
813 * <code>{@link #paramNames}</code>.</li>
815 * @param {Object} options An object containing properties which control loading options:<ul>
816 * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
817 * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
818 * <code>{@link #baseParams}</code> of the same name.</p>
819 * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
820 * <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
821 * have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
822 * <li>r : Ext.data.Record[] An Array of Records loaded.</li>
823 * <li>options : Options object from the load call.</li>
824 * <li>success : Boolean success indicator.</li></ul></p></div></li>
825 * <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
826 * to the Store object)</p></div></li>
827 * <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
828 * replace the current cache. <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
830 * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
831 * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
833 load : function(options) {
834 options = Ext.apply({}, options);
835 this.storeOptions(options);
836 if(this.sortInfo && this.remoteSort){
837 var pn = this.paramNames;
838 options.params = Ext.apply({}, options.params);
839 options.params[pn.sort] = this.sortInfo.field;
840 options.params[pn.dir] = this.sortInfo.direction;
843 return this.execute('read', null, options); // <-- null represents rs. No rs for load actions.
845 this.handleException(e);
851 * updateRecord Should not be used directly. This method will be called automatically if a Writer is set.
852 * Listens to 'update' event.
853 * @param {Object} store
854 * @param {Object} record
855 * @param {Object} action
858 updateRecord : function(store, record, action) {
859 if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
865 * Should not be used directly. Store#add will call this automatically if a Writer is set
866 * @param {Object} store
868 * @param {Object} index
871 createRecords : function(store, rs, index) {
872 for (var i = 0, len = rs.length; i < len; i++) {
873 if (rs[i].phantom && rs[i].isValid()) {
874 rs[i].markDirty(); // <-- Mark new records dirty
875 this.modified.push(rs[i]); // <-- add to modified
878 if (this.autoSave === true) {
884 * Destroys a Record. Should not be used directly. It's called by Store#remove if a Writer is set.
885 * @param {Store} store this
886 * @param {Ext.data.Record} record
887 * @param {Number} index
890 destroyRecord : function(store, record, index) {
891 if (this.modified.indexOf(record) != -1) { // <-- handled already if @cfg pruneModifiedRecords == true
892 this.modified.remove(record);
894 if (!record.phantom) {
895 this.removed.push(record);
897 // since the record has already been removed from the store but the server request has not yet been executed,
898 // must keep track of the last known index this record existed. If a server error occurs, the record can be
899 // put back into the store. @see Store#createCallback where the record is returned when response status === false
900 record.lastIndex = index;
902 if (this.autoSave === true) {
909 * This method should generally not be used directly. This method is called internally
910 * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
911 * {@link #remove}, or {@link #update} events fire.
912 * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
913 * @param {Record/Record[]} rs
914 * @param {Object} options
918 execute : function(action, rs, options, /* private */ batch) {
919 // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
920 if (!Ext.data.Api.isAction(action)) {
921 throw new Ext.data.Api.Error('execute', action);
923 // make sure options has a fresh, new params hash
924 options = Ext.applyIf(options||{}, {
927 if(batch !== undefined){
928 this.addToBatch(batch);
930 // have to separate before-events since load has a different signature than create,destroy and save events since load does not
931 // include the rs (record resultset) parameter. Capture return values from the beforeaction into doRequest flag.
932 var doRequest = true;
934 if (action === 'read') {
935 doRequest = this.fireEvent('beforeload', this, options);
936 Ext.applyIf(options.params, this.baseParams);
939 // if Writer is configured as listful, force single-record rs to be [{}] instead of {}
940 // TODO Move listful rendering into DataWriter where the @cfg is defined. Should be easy now.
941 if (this.writer.listful === true && this.restful !== true) {
942 rs = (Ext.isArray(rs)) ? rs : [rs];
944 // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
945 else if (Ext.isArray(rs) && rs.length == 1) {
948 // Write the action to options.params
949 if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
950 this.writer.apply(options.params, this.baseParams, action, rs);
953 if (doRequest !== false) {
954 // Send request to proxy.
955 if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
956 options.params.xaction = action; // <-- really old, probaby unecessary.
958 // Note: Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
959 // We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
960 // the user's configured DataProxy#api
961 // TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
962 // of params. This method is an artifact from Ext2.
963 this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
968 <div id="method-Ext.data.Store-save"></div>/**
969 * Saves all pending changes to the store. If the commensurate Ext.data.Api.actions action is not configured, then
970 * the configured <code>{@link #url}</code> will be used.
973 * --------------- --------------------
974 * removed records Ext.data.Api.actions.destroy
975 * phantom records Ext.data.Api.actions.create
976 * {@link #getModifiedRecords modified records} Ext.data.Api.actions.update
978 * @TODO: Create extensions of Error class and send associated Record with thrown exceptions.
979 * e.g.: Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
980 * @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
981 * if there are no items to save or the save was cancelled.
985 throw new Ext.data.Store.Error('writer-undefined');
993 // DESTROY: First check for removed records. Records in this.removed are guaranteed non-phantoms. @see Store#remove
994 if(this.removed.length){
995 queue.push(['destroy', this.removed]);
998 // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
999 var rs = [].concat(this.getModifiedRecords());
1001 // CREATE: Next check for phantoms within rs. splice-off and execute create.
1003 for(var i = rs.length-1; i >= 0; i--){
1004 if(rs[i].phantom === true){
1005 var rec = rs.splice(i, 1).shift();
1009 }else if(!rs[i].isValid()){ // <-- while we're here, splice-off any !isValid real records
1013 // If we have valid phantoms, create them...
1014 if(phantoms.length){
1015 queue.push(['create', phantoms]);
1018 // UPDATE: And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
1020 queue.push(['update', rs]);
1025 batch = ++this.batchCounter;
1026 for(var i = 0; i < len; ++i){
1028 data[trans[0]] = trans[1];
1030 if(this.fireEvent('beforesave', this, data) !== false){
1031 for(var i = 0; i < len; ++i){
1033 this.doTransaction(trans[0], trans[1], batch);
1041 // private. Simply wraps call to Store#execute in try/catch. Defers to Store#handleException on error. Loops if batch: false
1042 doTransaction : function(action, rs, batch) {
1043 function transaction(records) {
1045 this.execute(action, records, undefined, batch);
1047 this.handleException(e);
1050 if(this.batch === false){
1051 for(var i = 0, len = rs.length; i < len; i++){
1052 transaction.call(this, rs[i]);
1055 transaction.call(this, rs);
1060 addToBatch : function(batch){
1061 var b = this.batches,
1062 key = this.batchKey + batch,
1075 removeFromBatch : function(batch, action, data){
1076 var b = this.batches,
1077 key = this.batchKey + batch,
1084 arr = o.data[action] || [];
1085 o.data[action] = arr.concat(data);
1089 this.fireEvent('save', this, batch, data);
1096 // @private callback-handler for remote CRUD actions
1097 // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1098 createCallback : function(action, rs, batch) {
1099 var actions = Ext.data.Api.actions;
1100 return (action == 'read') ? this.loadRecords : function(data, response, success) {
1101 // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1102 this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
1103 // If success === false here, exception will have been called in DataProxy
1104 if (success === true) {
1105 this.fireEvent('write', this, action, data, response, rs);
1107 this.removeFromBatch(batch, action, data);
1111 // Clears records from modified array after an exception event.
1112 // NOTE: records are left marked dirty. Do we want to commit them even though they were not updated/realized?
1113 // TODO remove this method?
1114 clearModified : function(rs) {
1115 if (Ext.isArray(rs)) {
1116 for (var n=rs.length-1;n>=0;n--) {
1117 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1120 this.modified.splice(this.modified.indexOf(rs), 1);
1124 // remap record ids in MixedCollection after records have been realized. @see Store#onCreateRecords, @see DataReader#realize
1125 reMap : function(record) {
1126 if (Ext.isArray(record)) {
1127 for (var i = 0, len = record.length; i < len; i++) {
1128 this.reMap(record[i]);
1131 delete this.data.map[record._phid];
1132 this.data.map[record.id] = record;
1133 var index = this.data.keys.indexOf(record._phid);
1134 this.data.keys.splice(index, 1, record.id);
1135 delete record._phid;
1139 // @protected onCreateRecord proxy callback for create action
1140 onCreateRecords : function(success, rs, data) {
1141 if (success === true) {
1143 this.reader.realize(rs, data);
1147 this.handleException(e);
1148 if (Ext.isArray(rs)) {
1149 // Recurse to run back into the try {}. DataReader#realize splices-off the rs until empty.
1150 this.onCreateRecords(success, rs, data);
1156 // @protected, onUpdateRecords proxy callback for update action
1157 onUpdateRecords : function(success, rs, data) {
1158 if (success === true) {
1160 this.reader.update(rs, data);
1162 this.handleException(e);
1163 if (Ext.isArray(rs)) {
1164 // Recurse to run back into the try {}. DataReader#update splices-off the rs until empty.
1165 this.onUpdateRecords(success, rs, data);
1171 // @protected onDestroyRecords proxy callback for destroy action
1172 onDestroyRecords : function(success, rs, data) {
1173 // splice each rec out of this.removed
1174 rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
1175 for (var i=0,len=rs.length;i<len;i++) {
1176 this.removed.splice(this.removed.indexOf(rs[i]), 1);
1178 if (success === false) {
1179 // put records back into store if remote destroy fails.
1180 // @TODO: Might want to let developer decide.
1181 for (i=rs.length-1;i>=0;i--) {
1182 this.insert(rs[i].lastIndex, rs[i]); // <-- lastIndex set in Store#destroyRecord
1187 // protected handleException. Possibly temporary until Ext framework has an exception-handler.
1188 handleException : function(e) {
1189 // @see core/Error.js
1193 <div id="method-Ext.data.Store-reload"></div>/**
1194 * <p>Reloads the Record cache from the configured Proxy using the configured
1195 * {@link Ext.data.Reader Reader} and the options from the last load operation
1197 * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1198 * @param {Object} options <p>(optional) An <tt>Object</tt> containing
1199 * {@link #load loading options} which may override the {@link #lastOptions options}
1200 * used in the last {@link #load} operation. See {@link #load} for details
1201 * (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
1203 * <br><p>To add new params to the existing params:</p><pre><code>
1204 lastOptions = myStore.lastOptions;
1205 Ext.apply(lastOptions.params, {
1208 myStore.reload(lastOptions);
1211 reload : function(options){
1212 this.load(Ext.applyIf(options||{}, this.lastOptions));
1216 // Called as a callback by the Reader during a load operation.
1217 loadRecords : function(o, options, success){
1218 if (this.isDestroyed === true) {
1221 if(!o || success === false){
1222 if(success !== false){
1223 this.fireEvent('load', this, [], options);
1225 if(options.callback){
1226 options.callback.call(options.scope || this, [], options, false, o);
1230 var r = o.records, t = o.totalRecords || r.length;
1231 if(!options || options.add !== true){
1232 if(this.pruneModifiedRecords){
1235 for(var i = 0, len = r.length; i < len; i++){
1239 this.data = this.snapshot;
1240 delete this.snapshot;
1243 this.data.addAll(r);
1244 this.totalLength = t;
1246 this.fireEvent('datachanged', this);
1248 this.totalLength = Math.max(t, this.data.length+r.length);
1251 this.fireEvent('load', this, r, options);
1252 if(options.callback){
1253 options.callback.call(options.scope || this, r, options, true);
1257 <div id="method-Ext.data.Store-loadData"></div>/**
1258 * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1259 * which understands the format of the data must have been configured in the constructor.
1260 * @param {Object} data The data block from which to read the Records. The format of the data expected
1261 * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1262 * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1263 * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1264 * the existing cache.
1265 * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1266 * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1267 * new, unique ids will be added.
1269 loadData : function(o, append){
1270 var r = this.reader.readRecords(o);
1271 this.loadRecords(r, {add: append}, true);
1274 <div id="method-Ext.data.Store-getCount"></div>/**
1275 * Gets the number of cached records.
1276 * <p>If using paging, this may not be the total size of the dataset. If the data object
1277 * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1278 * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
1279 * @return {Number} The number of Records in the Store's cache.
1281 getCount : function(){
1282 return this.data.length || 0;
1285 <div id="method-Ext.data.Store-getTotalCount"></div>/**
1286 * Gets the total number of records in the dataset as returned by the server.
1287 * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1288 * must contain the dataset size. For remote data sources, the value for this property
1289 * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1290 * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1291 * <b>Note</b>: see the Important note in {@link #load}.</p>
1292 * @return {Number} The number of Records as specified in the data object passed to the Reader
1294 * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1296 getTotalCount : function(){
1297 return this.totalLength || 0;
1300 <div id="method-Ext.data.Store-getSortState"></div>/**
1301 * Returns an object describing the current sort state of this Store.
1302 * @return {Object} The sort state of the Store. An object with two properties:<ul>
1303 * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1304 * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1306 * See <tt>{@link #sortInfo}</tt> for additional details.
1308 getSortState : function(){
1309 return this.sortInfo;
1314 * Invokes sortData if we have sortInfo to sort on and are not sorting remotely
1316 applySort : function(){
1317 if ((this.sortInfo || this.multiSortInfo) && !this.remoteSort) {
1324 * Performs the actual sorting of data. This checks to see if we currently have a multi sort or not. It applies
1325 * each sorter field/direction pair in turn by building an OR'ed master sorting function and running it against
1328 sortData : function() {
1329 var sortInfo = this.hasMultiSort ? this.multiSortInfo : this.sortInfo,
1330 direction = sortInfo.direction || "ASC",
1331 sorters = sortInfo.sorters,
1334 //if we just have a single sorter, pretend it's the first in an array
1335 if (!this.hasMultiSort) {
1336 sorters = [{direction: direction, field: sortInfo.field}];
1339 //create a sorter function for each sorter field/direction combo
1340 for (var i=0, j = sorters.length; i < j; i++) {
1341 sortFns.push(this.createSortFunction(sorters[i].field, sorters[i].direction));
1344 if (sortFns.length == 0) {
1348 //the direction modifier is multiplied with the result of the sorting functions to provide overall sort direction
1349 //(as opposed to direction per field)
1350 var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
1352 //create a function which ORs each sorter together to enable multi-sort
1353 var fn = function(r1, r2) {
1354 var result = sortFns[0].call(this, r1, r2);
1356 //if we have more than one sorter, OR any additional sorter functions together
1357 if (sortFns.length > 1) {
1358 for (var i=1, j = sortFns.length; i < j; i++) {
1359 result = result || sortFns[i].call(this, r1, r2);
1363 return directionModifier * result;
1367 this.data.sort(direction, fn);
1368 if (this.snapshot && this.snapshot != this.data) {
1369 this.snapshot.sort(direction, fn);
1375 * Creates and returns a function which sorts an array by the given field and direction
1376 * @param {String} field The field to create the sorter for
1377 * @param {String} direction The direction to sort by (defaults to "ASC")
1378 * @return {Function} A function which sorts by the field/direction combination provided
1380 createSortFunction: function(field, direction) {
1381 direction = direction || "ASC";
1382 var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
1384 var sortType = this.fields.get(field).sortType;
1386 //create a comparison function. Takes 2 records, returns 1 if record 1 is greater,
1387 //-1 if record 2 is greater or 0 if they are equal
1388 return function(r1, r2) {
1389 var v1 = sortType(r1.data[field]),
1390 v2 = sortType(r2.data[field]);
1392 return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0));
1396 <div id="method-Ext.data.Store-setDefaultSort"></div>/**
1397 * Sets the default sort column and order to be used by the next {@link #load} operation.
1398 * @param {String} fieldName The name of the field to sort by.
1399 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1401 setDefaultSort : function(field, dir) {
1402 dir = dir ? dir.toUpperCase() : 'ASC';
1403 this.sortInfo = {field: field, direction: dir};
1404 this.sortToggle[field] = dir;
1407 <div id="method-Ext.data.Store-sort"></div>/**
1409 * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1410 * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1411 * This function accepts two call signatures - pass in a field name as the first argument to sort on a single
1412 * field, or pass in an array of sort configuration objects to sort by multiple fields.
1413 * Single sort example:
1414 * store.sort('name', 'ASC');
1415 * Multi sort example:
1426 * In this second form, the sort configs are applied in order, with later sorters sorting within earlier sorters' results.
1427 * For example, if two records with the same name are present they will also be sorted by salary if given the sort configs
1428 * above. Any number of sort configs can be added.
1429 * @param {String/Array} fieldName The name of the field to sort by, or an array of ordered sort configs
1430 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1432 sort : function(fieldName, dir) {
1433 if (Ext.isArray(arguments[0])) {
1434 return this.multiSort.call(this, fieldName, dir);
1436 return this.singleSort(fieldName, dir);
1440 <div id="method-Ext.data.Store-singleSort"></div>/**
1441 * Sorts the store contents by a single field and direction. This is called internally by {@link sort} and would
1442 * not usually be called manually
1443 * @param {String} fieldName The name of the field to sort by.
1444 * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1446 singleSort: function(fieldName, dir) {
1447 var field = this.fields.get(fieldName);
1448 if (!field) return false;
1450 var name = field.name,
1451 sortInfo = this.sortInfo || null,
1452 sortToggle = this.sortToggle ? this.sortToggle[name] : null;
1455 if (sortInfo && sortInfo.field == name) { // toggle sort dir
1456 dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
1458 dir = field.sortDir;
1462 this.sortToggle[name] = dir;
1463 this.sortInfo = {field: name, direction: dir};
1464 this.hasMultiSort = false;
1466 if (this.remoteSort) {
1467 if (!this.load(this.lastOptions)) {
1469 this.sortToggle[name] = sortToggle;
1472 this.sortInfo = sortInfo;
1477 this.fireEvent('datachanged', this);
1481 <div id="method-Ext.data.Store-multiSort"></div>/**
1482 * Sorts the contents of this store by multiple field/direction sorters. This is called internally by {@link sort}
1483 * and would not usually be called manually.
1484 * Multi sorting only currently applies to local datasets - multiple sort data is not currently sent to a proxy
1485 * if remoteSort is used.
1486 * @param {Array} sorters Array of sorter objects (field and direction)
1487 * @param {String} direction Overall direction to sort the ordered results by (defaults to "ASC")
1489 multiSort: function(sorters, direction) {
1490 this.hasMultiSort = true;
1491 direction = direction || "ASC";
1493 //toggle sort direction
1494 if (this.multiSortInfo && direction == this.multiSortInfo.direction) {
1495 direction = direction.toggle("ASC", "DESC");
1498 <div id="prop-Ext.data.Store-multiSortInfo"></div>/**
1499 * Object containing overall sort direction and an ordered array of sorter configs used when sorting on multiple fields
1500 * @property multiSortInfo
1503 this.multiSortInfo = {
1505 direction: direction
1508 if (this.remoteSort) {
1509 this.singleSort(sorters[0].field, sorters[0].direction);
1513 this.fireEvent('datachanged', this);
1517 <div id="method-Ext.data.Store-each"></div>/**
1518 * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1519 * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1520 * Returning <tt>false</tt> aborts and exits the iteration.
1521 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
1522 * Defaults to the current {@link Ext.data.Record Record} in the iteration.
1524 each : function(fn, scope){
1525 this.data.each(fn, scope);
1528 <div id="method-Ext.data.Store-getModifiedRecords"></div>/**
1529 * Gets all {@link Ext.data.Record records} modified since the last commit. Modified records are
1530 * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1531 * included. See also <tt>{@link #pruneModifiedRecords}</tt> and
1532 * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1533 * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1534 * modifications. To obtain modified fields within a modified record see
1535 *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1537 getModifiedRecords : function(){
1538 return this.modified;
1541 <div id="method-Ext.data.Store-sum"></div>/**
1542 * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1543 * and <tt>end</tt> and returns the result.
1544 * @param {String} property A field in each record
1545 * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1546 * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1547 * @return {Number} The sum
1549 sum : function(property, start, end){
1550 var rs = this.data.items, v = 0;
1552 end = (end || end === 0) ? end : rs.length-1;
1554 for(var i = start; i <= end; i++){
1555 v += (rs[i].data[property] || 0);
1562 * Returns a filter function used to test a the given property's value. Defers most of the work to
1563 * Ext.util.MixedCollection's createValueMatcher function
1564 * @param {String} property The property to create the filter function for
1565 * @param {String/RegExp} value The string/regex to compare the property value to
1566 * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
1567 * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
1568 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
1570 createFilterFn : function(property, value, anyMatch, caseSensitive, exactMatch){
1571 if(Ext.isEmpty(value, false)){
1574 value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
1575 return function(r) {
1576 return value.test(r.data[property]);
1582 * Given an array of filter functions (each with optional scope), constructs and returns a single function that returns
1583 * the result of all of the filters ANDed together
1584 * @param {Array} filters The array of filter objects (each object should contain an 'fn' and optional scope)
1585 * @return {Function} The multiple filter function
1587 createMultipleFilterFn: function(filters) {
1588 return function(record) {
1591 for (var i=0, j = filters.length; i < j; i++) {
1592 var filter = filters[i],
1594 scope = filter.scope;
1596 isMatch = isMatch && fn.call(scope, record);
1603 <div id="method-Ext.data.Store-filter"></div>/**
1604 * Filter the {@link Ext.data.Record records} by a specified property. Alternatively, pass an array of filter
1605 * options to filter by more than one property.
1606 * Single filter example:
1607 * store.filter('name', 'Ed', true, true); //finds all records containing the substring 'Ed'
1608 * Multiple filter example:
1612 * property : 'name',
1614 * anyMatch : true, //optional, defaults to true
1615 * caseSensitive: true //optional, defaults to true
1618 * //filter functions can also be passed
1620 * fn : function(record) {
1621 * return record.get('age') == 24
1627 * @param {String|Array} field A field on your records, or an array containing multiple filter options
1628 * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1629 * against the field.
1630 * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1631 * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1632 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
1634 filter : function(property, value, anyMatch, caseSensitive, exactMatch){
1635 //we can accept an array of filter objects, or a single filter object - normalize them here
1636 if (Ext.isObject(property)) {
1637 property = [property];
1640 if (Ext.isArray(property)) {
1643 //normalize the filters passed into an array of filter functions
1644 for (var i=0, j = property.length; i < j; i++) {
1645 var filter = property[i],
1647 scope = filter.scope || this;
1649 //if we weren't given a filter function, construct one now
1650 if (!Ext.isFunction(func)) {
1651 func = this.createFilterFn(filter.property, filter.value, filter.anyMatch, filter.caseSensitive, filter.exactMatch);
1654 filters.push({fn: func, scope: scope});
1657 var fn = this.createMultipleFilterFn(filters);
1659 //classic single property filter
1660 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
1663 return fn ? this.filterBy(fn) : this.clearFilter();
1666 <div id="method-Ext.data.Store-filterBy"></div>/**
1667 * Filter by a function. The specified function will be called for each
1668 * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1669 * otherwise it is filtered out.
1670 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1671 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1672 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1673 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1675 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1677 filterBy : function(fn, scope){
1678 this.snapshot = this.snapshot || this.data;
1679 this.data = this.queryBy(fn, scope||this);
1680 this.fireEvent('datachanged', this);
1683 <div id="method-Ext.data.Store-clearFilter"></div>/**
1684 * Revert to a view of the Record cache with no filtering applied.
1685 * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1686 * {@link #datachanged} event.
1688 clearFilter : function(suppressEvent){
1689 if(this.isFiltered()){
1690 this.data = this.snapshot;
1691 delete this.snapshot;
1692 if(suppressEvent !== true){
1693 this.fireEvent('datachanged', this);
1698 <div id="method-Ext.data.Store-isFiltered"></div>/**
1699 * Returns true if this store is currently filtered
1702 isFiltered : function(){
1703 return !!this.snapshot && this.snapshot != this.data;
1706 <div id="method-Ext.data.Store-query"></div>/**
1707 * Query the records by a specified property.
1708 * @param {String} field A field on your records
1709 * @param {String/RegExp} value Either a string that the field
1710 * should begin with, or a RegExp to test against the field.
1711 * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
1712 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1713 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1715 query : function(property, value, anyMatch, caseSensitive){
1716 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1717 return fn ? this.queryBy(fn) : this.data.clone();
1720 <div id="method-Ext.data.Store-queryBy"></div>/**
1721 * Query the cached records in this Store using a filtering function. The specified function
1722 * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1723 * included in the results.
1724 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1725 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1726 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1727 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1729 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1730 * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1732 queryBy : function(fn, scope){
1733 var data = this.snapshot || this.data;
1734 return data.filterBy(fn, scope||this);
1737 <div id="method-Ext.data.Store-find"></div>/**
1738 * Finds the index of the first matching Record in this store by a specific field value.
1739 * @param {String} fieldName The name of the Record field to test.
1740 * @param {String/RegExp} value Either a string that the field value
1741 * should begin with, or a RegExp to test against the field.
1742 * @param {Number} startIndex (optional) The index to start searching at
1743 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1744 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1745 * @return {Number} The matched index or -1
1747 find : function(property, value, start, anyMatch, caseSensitive){
1748 var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1749 return fn ? this.data.findIndexBy(fn, null, start) : -1;
1752 <div id="method-Ext.data.Store-findExact"></div>/**
1753 * Finds the index of the first matching Record in this store by a specific field value.
1754 * @param {String} fieldName The name of the Record field to test.
1755 * @param {Mixed} value The value to match the field against.
1756 * @param {Number} startIndex (optional) The index to start searching at
1757 * @return {Number} The matched index or -1
1759 findExact: function(property, value, start){
1760 return this.data.findIndexBy(function(rec){
1761 return rec.get(property) === value;
1765 <div id="method-Ext.data.Store-findBy"></div>/**
1766 * Find the index of the first matching Record in this Store by a function.
1767 * If the function returns <tt>true</tt> it is considered a match.
1768 * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1769 * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1770 * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1771 * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1773 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1774 * @param {Number} startIndex (optional) The index to start searching at
1775 * @return {Number} The matched index or -1
1777 findBy : function(fn, scope, start){
1778 return this.data.findIndexBy(fn, scope, start);
1781 <div id="method-Ext.data.Store-collect"></div>/**
1782 * Collects unique values for a particular dataIndex from this store.
1783 * @param {String} dataIndex The property to collect
1784 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1785 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1786 * @return {Array} An array of the unique values
1788 collect : function(dataIndex, allowNull, bypassFilter){
1789 var d = (bypassFilter === true && this.snapshot) ?
1790 this.snapshot.items : this.data.items;
1791 var v, sv, r = [], l = {};
1792 for(var i = 0, len = d.length; i < len; i++){
1793 v = d[i].data[dataIndex];
1795 if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
1804 afterEdit : function(record){
1805 if(this.modified.indexOf(record) == -1){
1806 this.modified.push(record);
1808 this.fireEvent('update', this, record, Ext.data.Record.EDIT);
1812 afterReject : function(record){
1813 this.modified.remove(record);
1814 this.fireEvent('update', this, record, Ext.data.Record.REJECT);
1818 afterCommit : function(record){
1819 this.modified.remove(record);
1820 this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
1823 <div id="method-Ext.data.Store-commitChanges"></div>/**
1824 * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
1825 * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
1826 * Ext.data.Record.COMMIT.
1828 commitChanges : function(){
1829 var m = this.modified.slice(0);
1831 for(var i = 0, len = m.length; i < len; i++){
1836 <div id="method-Ext.data.Store-rejectChanges"></div>/**
1837 * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
1839 rejectChanges : function(){
1840 var m = this.modified.slice(0);
1842 for(var i = 0, len = m.length; i < len; i++){
1845 var m = this.removed.slice(0).reverse();
1847 for(var i = 0, len = m.length; i < len; i++){
1848 this.insert(m[i].lastIndex||0, m[i]);
1854 onMetaChange : function(meta){
1855 this.recordType = this.reader.recordType;
1856 this.fields = this.recordType.prototype.fields;
1857 delete this.snapshot;
1858 if(this.reader.meta.sortInfo){
1859 this.sortInfo = this.reader.meta.sortInfo;
1860 }else if(this.sortInfo && !this.fields.get(this.sortInfo.field)){
1861 delete this.sortInfo;
1864 this.writer.meta = this.reader.meta;
1867 this.fireEvent('metachange', this, this.reader.meta);
1871 findInsertIndex : function(record){
1872 this.suspendEvents();
1873 var data = this.data.clone();
1874 this.data.add(record);
1876 var index = this.data.indexOf(record);
1878 this.resumeEvents();
1882 <div id="method-Ext.data.Store-setBaseParam"></div>/**
1883 * Set the value for a property name in this store's {@link #baseParams}. Usage:</p><pre><code>
1884 myStore.setBaseParam('foo', {bar:3});
1886 * @param {String} name Name of the property to assign
1887 * @param {Mixed} value Value to assign the <tt>name</tt>d property
1889 setBaseParam : function (name, value){
1890 this.baseParams = this.baseParams || {};
1891 this.baseParams[name] = value;
1895 Ext.reg('store', Ext.data.Store);
1897 <div id="cls-Ext.data.Store.Error"></div>/**
1898 * @class Ext.data.Store.Error
1899 * @extends Ext.Error
1900 * Store Error extension.
1901 * @param {String} name
1903 Ext.data.Store.Error = Ext.extend(Ext.Error, {
1904 name: 'Ext.data.Store'
1906 Ext.apply(Ext.data.Store.Error.prototype, {
1908 'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'