source: trunk/web/addons/job_monarch/lib/extjs-30/src/data/Store.js @ 625

Last change on this file since 625 was 625, checked in by ramonb, 15 years ago

lib/extjs-30:

  • new ExtJS 3.0
File size: 60.6 KB
Line 
1/*!
2 * Ext JS Library 3.0.0
3 * Copyright(c) 2006-2009 Ext JS, LLC
4 * licensing@extjs.com
5 * http://www.extjs.com/license
6 */
7/**
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>
18 * </ul></div></p>
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
23 * object.</p>
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>
28 * <pre><code>
29var myStore = new Ext.data.ArrayStore({
30    fields: ['fullname', 'first'],
31    idIndex: 0 // id for each record will be the first element
32});
33 * </code></pre>
34 * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
35 * <pre><code>
36// create a {@link Ext.data.Record Record} constructor:
37var rt = Ext.data.Record.create([
38    {name: 'fullname'},
39    {name: 'first'}
40]);
41var myStore = new Ext.data.Store({
42    // explicitly create reader
43    reader: new Ext.data.ArrayReader(
44        {
45            idIndex: 0  // id for each record will be the first element
46        },
47        rt // recordType
48    )
49});
50 * </code></pre>
51 * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
52 * <pre><code>
53var myData = [
54    [1, 'Fred Flintstone', 'Fred'],  // note that id for the record is the first element
55    [2, 'Barney Rubble', 'Barney']
56];
57myStore.loadData(myData);
58 * </code></pre>
59 * <p>Records are cached and made available through accessor functions.  An example of adding
60 * a record to the store:</p>
61 * <pre><code>
62var defaultData = {
63    fullname: 'Full Name',
64    first: 'First Name'
65};
66var recId = 100; // provide unique id for the record
67var r = new myStore.recordType(defaultData, ++recId); // create new record
68myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
69 * </code></pre>
70 * @constructor
71 * Creates a new Store.
72 * @param {Object} config A config object containing the objects needed for the Store to access data,
73 * and read the data into Records.
74 * @xtype store
75 */
76Ext.data.Store = function(config){
77    this.data = new Ext.util.MixedCollection(false);
78    this.data.getKey = function(o){
79        return o.id;
80    };
81    /**
82     * See the <code>{@link #baseParams corresponding configuration option}</code>
83     * for a description of this property.
84     * To modify this property see <code>{@link #setBaseParam}</code>.
85     * @property
86     */
87    this.baseParams = {};
88
89    // temporary removed-records cache
90    this.removed = [];
91
92    if(config && config.data){
93        this.inlineData = config.data;
94        delete config.data;
95    }
96
97    Ext.apply(this, config);
98   
99    this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
100
101    if(this.url && !this.proxy){
102        this.proxy = new Ext.data.HttpProxy({url: this.url});
103    }
104    // If Store is RESTful, so too is the DataProxy
105    if (this.restful === true && this.proxy) {
106        // When operating RESTfully, a unique transaction is generated for each record.
107        this.batch = false;
108        Ext.data.Api.restify(this.proxy);
109    }
110
111    if(this.reader){ // reader passed
112        if(!this.recordType){
113            this.recordType = this.reader.recordType;
114        }
115        if(this.reader.onMetaChange){
116            this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
117        }
118        if (this.writer) { // writer passed
119            this.writer.meta = this.reader.meta;
120            this.pruneModifiedRecords = true;
121        }
122    }
123
124    /**
125     * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
126     * {@link Ext.data.DataReader Reader}. Read-only.
127     * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
128     * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
129     * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
130     * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
131// create the data store
132var store = new Ext.data.ArrayStore({
133    autoDestroy: true,
134    fields: [
135       {name: 'company'},
136       {name: 'price', type: 'float'},
137       {name: 'change', type: 'float'},
138       {name: 'pctChange', type: 'float'},
139       {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
140    ]
141});
142store.loadData(myData);
143
144// create the Grid
145var grid = new Ext.grid.EditorGridPanel({
146    store: store,
147    colModel: new Ext.grid.ColumnModel({
148        columns: [
149            {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
150            {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
151            {header: 'Change', renderer: change, dataIndex: 'change'},
152            {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
153            {header: 'Last Updated', width: 85,
154                renderer: Ext.util.Format.dateRenderer('m/d/Y'),
155                dataIndex: 'lastChange'}
156        ],
157        defaults: {
158            sortable: true,
159            width: 75
160        }
161    }),
162    autoExpandColumn: 'company', // match the id specified in the column model
163    height:350,
164    width:600,
165    title:'Array Grid',
166    tbar: [{
167        text: 'Add Record',
168        handler : function(){
169            var defaultData = {
170                change: 0,
171                company: 'New Company',
172                lastChange: (new Date()).clearTime(),
173                pctChange: 0,
174                price: 10
175            };
176            var recId = 3; // provide unique id
177            var p = new store.recordType(defaultData, recId); // create new record
178            grid.stopEditing();
179            store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
180            grid.startEditing(0, 0);
181        }
182    }]
183});
184     * </code></pre>
185     * @property recordType
186     * @type Function
187     */
188
189    if(this.recordType){
190        /**
191         * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
192         * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
193         * @property fields
194         * @type Ext.util.MixedCollection
195         */
196        this.fields = this.recordType.prototype.fields;
197    }
198    this.modified = [];
199
200    this.addEvents(
201        /**
202         * @event datachanged
203         * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
204         * widget that is using this Store as a Record cache should refresh its view.
205         * @param {Store} this
206         */
207        'datachanged',
208        /**
209         * @event metachange
210         * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
211         * @param {Store} this
212         * @param {Object} meta The JSON metadata
213         */
214        'metachange',
215        /**
216         * @event add
217         * Fires when Records have been {@link #add}ed to the Store
218         * @param {Store} this
219         * @param {Ext.data.Record[]} records The array of Records added
220         * @param {Number} index The index at which the record(s) were added
221         */
222        'add',
223        /**
224         * @event remove
225         * Fires when a Record has been {@link #remove}d from the Store
226         * @param {Store} this
227         * @param {Ext.data.Record} record The Record that was removed
228         * @param {Number} index The index at which the record was removed
229         */
230        'remove',
231        /**
232         * @event update
233         * Fires when a Record has been updated
234         * @param {Store} this
235         * @param {Ext.data.Record} record The Record that was updated
236         * @param {String} operation The update operation being performed.  Value may be one of:
237         * <pre><code>
238 Ext.data.Record.EDIT
239 Ext.data.Record.REJECT
240 Ext.data.Record.COMMIT
241         * </code></pre>
242         */
243        'update',
244        /**
245         * @event clear
246         * Fires when the data cache has been cleared.
247         * @param {Store} this
248         */
249        'clear',
250        /**
251         * @event exception
252         * <p>Fires if an exception occurs in the Proxy during a remote request.
253         * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
254         * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
255         * for additional details.
256         * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
257         * for description.
258         */
259        'exception',
260        /**
261         * @event beforeload
262         * Fires before a request is made for a new data object.  If the beforeload handler returns
263         * <tt>false</tt> the {@link #load} action will be canceled.
264         * @param {Store} this
265         * @param {Object} options The loading options that were specified (see {@link #load} for details)
266         */
267        'beforeload',
268        /**
269         * @event load
270         * Fires after a new set of Records has been loaded.
271         * @param {Store} this
272         * @param {Ext.data.Record[]} records The Records that were loaded
273         * @param {Object} options The loading options that were specified (see {@link #load} for details)
274         */
275        'load',
276        /**
277         * @event loadexception
278         * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
279         * event instead.</p>
280         * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
281         * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
282         * for additional details.
283         * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
284         * for description.
285         */
286        'loadexception',
287        /**
288         * @event beforewrite
289         * @param {DataProxy} this
290         * @param {String} action [Ext.data.Api.actions.create|update|destroy]
291         * @param {Record/Array[Record]} rs
292         * @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)
293         * @param {Object} arg The callback's arg object passed to the {@link #request} function
294         */
295        'beforewrite',
296        /**
297         * @event write
298         * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
299         * Success or failure of the action is available in the <code>result['successProperty']</code> property.
300         * The server-code might set the <code>successProperty</code> to <tt>false</tt> if a database validation
301         * failed, for example.
302         * @param {Ext.data.Store} store
303         * @param {String} action [Ext.data.Api.actions.create|update|destroy]
304         * @param {Object} result The 'data' picked-out out of the response for convenience.
305         * @param {Ext.Direct.Transaction} res
306         * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
307         */
308        'write'
309    );
310
311    if(this.proxy){
312        this.relayEvents(this.proxy,  ['loadexception', 'exception']);
313    }
314    // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
315    if (this.writer) {
316        this.on({
317            scope: this,
318            add: this.createRecords,
319            remove: this.destroyRecord,
320            update: this.updateRecord
321        });
322    }
323
324    this.sortToggle = {};
325    if(this.sortField){
326        this.setDefaultSort(this.sortField, this.sortDir);
327    }else if(this.sortInfo){
328        this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
329    }
330
331    Ext.data.Store.superclass.constructor.call(this);
332
333    if(this.id){
334        this.storeId = this.id;
335        delete this.id;
336    }
337    if(this.storeId){
338        Ext.StoreMgr.register(this);
339    }
340    if(this.inlineData){
341        this.loadData(this.inlineData);
342        delete this.inlineData;
343    }else if(this.autoLoad){
344        this.load.defer(10, this, [
345            typeof this.autoLoad == 'object' ?
346                this.autoLoad : undefined]);
347    }
348};
349Ext.extend(Ext.data.Store, Ext.util.Observable, {
350    /**
351     * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
352     * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
353     * assignment.</p>
354     */
355    /**
356     * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
357     * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
358     * Typically this option, or the <code>{@link #data}</code> option will be specified.
359     */
360    /**
361     * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
362     * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
363     * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
364     * be passed to the store's {@link #load} method.
365     */
366    /**
367     * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
368     * access to a data object.  See <code>{@link #url}</code>.
369     */
370    /**
371     * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
372     * Typically this option, or the <code>{@link #url}</code> option will be specified.
373     */
374    /**
375     * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
376     * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
377     * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
378     */
379    /**
380     * @cfg {Ext.data.DataWriter} writer
381     * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
382     * to the server-side database.</p>
383     * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
384     * events on the store are monitored in order to remotely {@link #createRecords create records},
385     * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
386     * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
387     * <br><p>Sample implementation:
388     * <pre><code>
389var writer = new {@link Ext.data.JsonWriter}({
390    encode: true,
391    writeAllFields: true // write all fields, not just those that changed
392});
393
394// Typical Store collecting the Proxy, Reader and Writer together.
395var store = new Ext.data.Store({
396    storeId: 'user',
397    root: 'records',
398    proxy: proxy,
399    reader: reader,
400    writer: writer,     // <-- plug a DataWriter into the store just as you would a Reader
401    paramsAsHash: true,
402    autoSave: false    // <-- false to delay executing create, update, destroy requests
403                        //     until specifically told to do so.
404});
405     * </code></pre></p>
406     */
407    writer : undefined,
408    /**
409     * @cfg {Object} baseParams
410     * <p>An object containing properties which are to be sent as parameters
411     * for <i>every</i> HTTP request.</p>
412     * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
413     * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
414     * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
415     * for more details.</p>
416     * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
417     * method.
418     * @property
419     */
420    /**
421     * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
422     * {@link #load} operation.  Note that for local sorting, the <tt>direction</tt> property is
423     * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
424     * For example:<pre><code>
425sortInfo: {
426    field: 'fieldName',
427    direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
428}
429</code></pre>
430     */
431    /**
432     * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
433     * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
434     * in place (defaults to <tt>false</tt>).
435     * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
436     * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
437     * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
438     * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
439     * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
440     * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
441     * </ul></div></p>
442     */
443    remoteSort : false,
444
445    /**
446     * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
447     * to is destroyed (defaults to <tt>false</tt>).
448     * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
449     */
450    autoDestroy : false,
451
452    /**
453     * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
454     * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
455     * for the accessor method to retrieve the modified records.
456     */
457    pruneModifiedRecords : false,
458
459    /**
460     * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
461     * for the details of what this may contain. This may be useful for accessing any params which were used
462     * to load the current Record cache.
463     * @property
464     */
465    lastOptions : null,
466
467    /**
468     * @cfg {Boolean} autoSave
469     * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
470     * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
471     * to send all modifiedRecords to the server.</p>
472     * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
473     */
474    autoSave : true,
475
476    /**
477     * @cfg {Boolean} batch
478     * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
479     * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
480     * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
481     * to <tt>false</tt>.</p>
482     * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
483     * generated for each record.</p>
484     */
485    batch : true,
486
487    /**
488     * @cfg {Boolean} restful
489     * Defaults to <tt>false</tt>.  Set to <tt>true</tt> to have the Store and the set
490     * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
491     * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
492     * action is described in {@link Ext.data.Api#restActions}.  For additional information
493     * see {@link Ext.data.DataProxy#restful}.
494     * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
495     * internally be set to <tt>false</tt>.</p>
496     */
497    restful: false,
498   
499    /**
500     * @cfg {Object} paramNames
501     * <p>An object containing properties which specify the names of the paging and
502     * sorting parameters passed to remote servers when loading blocks of data. By default, this
503     * object takes the following form:</p><pre><code>
504{
505    start : 'start',  // The parameter name which specifies the start row
506    limit : 'limit',  // The parameter name which specifies number of rows to return
507    sort : 'sort',    // The parameter name which specifies the column to sort on
508    dir : 'dir'       // The parameter name which specifies the sort direction
509}
510</code></pre>
511     * <p>The server must produce the requested data block upon receipt of these parameter names.
512     * If different parameter names are required, this property can be overriden using a configuration
513     * property.</p>
514     * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
515     * the parameter names to use in its {@link #load requests}.
516     */
517    paramNames : undefined,
518   
519    /**
520     * @cfg {Object} defaultParamNames
521     * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
522     * for all stores, this object should be changed on the store prototype.
523     */
524    defaultParamNames : {
525        start : 'start',
526        limit : 'limit',
527        sort : 'sort',
528        dir : 'dir'
529    },
530
531    /**
532     * Destroys the store.
533     */
534    destroy : function(){
535        if(this.storeId){
536            Ext.StoreMgr.unregister(this);
537        }
538        this.data = null;
539        Ext.destroy(this.proxy);
540        this.reader = this.writer = null;
541        this.purgeListeners();
542    },
543
544    /**
545     * Add Records to the Store and fires the {@link #add} event.  To add Records
546     * to the store from a remote source use <code>{@link #load}({add:true})</code>.
547     * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
548     * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
549     * to add to the cache. See {@link #recordType}.
550     */
551    add : function(records){
552        records = [].concat(records);
553        if(records.length < 1){
554            return;
555        }
556        for(var i = 0, len = records.length; i < len; i++){
557            records[i].join(this);
558        }
559        var index = this.data.length;
560        this.data.addAll(records);
561        if(this.snapshot){
562            this.snapshot.addAll(records);
563        }
564        this.fireEvent('add', this, records, index);
565    },
566
567    /**
568     * (Local sort only) Inserts the passed Record into the Store at the index where it
569     * should go based on the current sort information.
570     * @param {Ext.data.Record} record
571     */
572    addSorted : function(record){
573        var index = this.findInsertIndex(record);
574        this.insert(index, record);
575    },
576
577    /**
578     * Remove a Record from the Store and fires the {@link #remove} event.
579     * @param {Ext.data.Record} record The Ext.data.Record object to remove from the cache.
580     */
581    remove : function(record){
582        var index = this.data.indexOf(record);
583        if(index > -1){
584            this.data.removeAt(index);
585            if(this.pruneModifiedRecords){
586                this.modified.remove(record);
587            }
588            if(this.snapshot){
589                this.snapshot.remove(record);
590            }
591            this.fireEvent('remove', this, record, index);
592        }
593    },
594
595    /**
596     * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
597     * @param {Number} index The index of the record to remove.
598     */
599    removeAt : function(index){
600        this.remove(this.getAt(index));
601    },
602
603    /**
604     * Remove all Records from the Store and fires the {@link #clear} event.
605     */
606    removeAll : function(){
607        this.data.clear();
608        if(this.snapshot){
609            this.snapshot.clear();
610        }
611        if(this.pruneModifiedRecords){
612            this.modified = [];
613        }
614        this.fireEvent('clear', this);
615    },
616
617    /**
618     * Inserts Records into the Store at the given index and fires the {@link #add} event.
619     * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
620     * @param {Number} index The start index at which to insert the passed Records.
621     * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
622     */
623    insert : function(index, records){
624        records = [].concat(records);
625        for(var i = 0, len = records.length; i < len; i++){
626            this.data.insert(index, records[i]);
627            records[i].join(this);
628        }
629        this.fireEvent('add', this, records, index);
630    },
631
632    /**
633     * Get the index within the cache of the passed Record.
634     * @param {Ext.data.Record} record The Ext.data.Record object to find.
635     * @return {Number} The index of the passed Record. Returns -1 if not found.
636     */
637    indexOf : function(record){
638        return this.data.indexOf(record);
639    },
640
641    /**
642     * Get the index within the cache of the Record with the passed id.
643     * @param {String} id The id of the Record to find.
644     * @return {Number} The index of the Record. Returns -1 if not found.
645     */
646    indexOfId : function(id){
647        return this.data.indexOfKey(id);
648    },
649
650    /**
651     * Get the Record with the specified id.
652     * @param {String} id The id of the Record to find.
653     * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
654     */
655    getById : function(id){
656        return this.data.key(id);
657    },
658
659    /**
660     * Get the Record at the specified index.
661     * @param {Number} index The index of the Record to find.
662     * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
663     */
664    getAt : function(index){
665        return this.data.itemAt(index);
666    },
667
668    /**
669     * Returns a range of Records between specified indices.
670     * @param {Number} startIndex (optional) The starting index (defaults to 0)
671     * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
672     * @return {Ext.data.Record[]} An array of Records
673     */
674    getRange : function(start, end){
675        return this.data.getRange(start, end);
676    },
677
678    // private
679    storeOptions : function(o){
680        o = Ext.apply({}, o);
681        delete o.callback;
682        delete o.scope;
683        this.lastOptions = o;
684    },
685
686    /**
687     * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
688     * <br><p>Notes:</p><div class="mdetail-params"><ul>
689     * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
690     * loaded. To perform any post-processing where information from the load call is required, specify
691     * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
692     * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
693     * properties in the <code>options.params</code> property to establish the initial position within the
694     * dataset, and the number of Records to cache on each read from the Proxy.</li>
695     * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
696     * will be automatically included with the posted parameters according to the specified
697     * <code>{@link #paramNames}</code>.</li>
698     * </ul></div>
699     * @param {Object} options An object containing properties which control loading options:<ul>
700     * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
701     * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
702     * <code>{@link #baseParams}</code> of the same name.</p>
703     * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
704     * <li><b><tt>callback</tt></b> : Function<div class="sub-desc"><p>A function to be called after the Records
705     * have been loaded. The <tt>callback</tt> is called after the load event and is passed the following arguments:<ul>
706     * <li><tt>r</tt> : Ext.data.Record[]</li>
707     * <li><tt>options</tt>: Options object from the load call</li>
708     * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div></li>
709     * <li><b><tt>scope</tt></b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
710     * to the Store object)</p></div></li>
711     * <li><b><tt>add</tt></b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
712     * replace the current cache.  <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
713     * </ul>
714     * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
715     * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
716     */
717    load : function(options) {
718        options = options || {};
719        this.storeOptions(options);
720        if(this.sortInfo && this.remoteSort){
721            var pn = this.paramNames;
722            options.params = options.params || {};
723            options.params[pn.sort] = this.sortInfo.field;
724            options.params[pn.dir] = this.sortInfo.direction;
725        }
726        try {
727            return this.execute('read', null, options); // <-- null represents rs.  No rs for load actions.
728        } catch(e) {
729            this.handleException(e);
730            return false;
731        }
732    },
733
734    /**
735     * updateRecord  Should not be used directly.  This method will be called automatically if a Writer is set.
736     * Listens to 'update' event.
737     * @param {Object} store
738     * @param {Object} record
739     * @param {Object} action
740     * @private
741     */
742    updateRecord : function(store, record, action) {
743        if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid))) {
744            this.save();
745        }
746    },
747
748    /**
749     * Should not be used directly.  Store#add will call this automatically if a Writer is set
750     * @param {Object} store
751     * @param {Object} rs
752     * @param {Object} index
753     * @private
754     */
755    createRecords : function(store, rs, index) {
756        for (var i = 0, len = rs.length; i < len; i++) {
757            if (rs[i].phantom && rs[i].isValid()) {
758                rs[i].markDirty();  // <-- Mark new records dirty
759                this.modified.push(rs[i]);  // <-- add to modified
760            }
761        }
762        if (this.autoSave === true) {
763            this.save();
764        }
765    },
766
767    /**
768     * Destroys a record or records.  Should not be used directly.  It's called by Store#remove if a Writer is set.
769     * @param {Store} this
770     * @param {Ext.data.Record/Ext.data.Record[]}
771     * @param {Number} index
772     * @private
773     */
774    destroyRecord : function(store, record, index) {
775        if (this.modified.indexOf(record) != -1) {  // <-- handled already if @cfg pruneModifiedRecords == true
776            this.modified.remove(record);
777        }
778        if (!record.phantom) {
779            this.removed.push(record);
780
781            // since the record has already been removed from the store but the server request has not yet been executed,
782            // must keep track of the last known index this record existed.  If a server error occurs, the record can be
783            // put back into the store.  @see Store#createCallback where the record is returned when response status === false
784            record.lastIndex = index;
785
786            if (this.autoSave === true) {
787                this.save();
788            }
789        }
790    },
791
792    /**
793     * This method should generally not be used directly.  This method is called internally
794     * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
795     * {@link #remove}, or {@link #update} events fire.
796     * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
797     * @param {Record/Record[]} rs
798     * @param {Object} options
799     * @throws Error
800     * @private
801     */
802    execute : function(action, rs, options) {
803        // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
804        if (!Ext.data.Api.isAction(action)) {
805            throw new Ext.data.Api.Error('execute', action);
806        }
807        // make sure options has a params key
808        options = Ext.applyIf(options||{}, {
809            params: {}
810        });
811
812        // have to separate before-events since load has a different signature than create,destroy and save events since load does not
813        // include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
814        var doRequest = true;
815
816        if (action === 'read') {
817            doRequest = this.fireEvent('beforeload', this, options);
818        }
819        else {
820            // if Writer is configured as listful, force single-recoord rs to be [{}} instead of {}
821            if (this.writer.listful === true && this.restful !== true) {
822                rs = (Ext.isArray(rs)) ? rs : [rs];
823            }
824            // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
825            else if (Ext.isArray(rs) && rs.length == 1) {
826                rs = rs.shift();
827            }
828            // Write the action to options.params
829            if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
830                this.writer.write(action, options.params, rs);
831            }
832        }
833        if (doRequest !== false) {
834            // Send request to proxy.
835            var params = Ext.apply({}, options.params, this.baseParams);
836            if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
837                params.xaction = action;
838            }
839            // Note:  Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.  We'll flip it now
840            // and send the value into DataProxy#request, since it's the value which maps to the DataProxy#api
841            this.proxy.request(Ext.data.Api.actions[action], rs, params, this.reader, this.createCallback(action, rs), this, options);
842        }
843        return doRequest;
844    },
845
846    /**
847     * Saves all pending changes to the store.  If the commensurate Ext.data.Api.actions action is not configured, then
848     * the configured <code>{@link #url}</code> will be used.
849     * <pre>
850     * change            url
851     * ---------------   --------------------
852     * removed records   Ext.data.Api.actions.destroy
853     * phantom records   Ext.data.Api.actions.create
854     * {@link #getModifiedRecords modified records}  Ext.data.Api.actions.update
855     * </pre>
856     * @TODO:  Create extensions of Error class and send associated Record with thrown exceptions.
857     * e.g.:  Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
858     */
859    save : function() {
860        if (!this.writer) {
861            throw new Ext.data.Store.Error('writer-undefined');
862        }
863
864        // DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
865        if (this.removed.length) {
866            this.doTransaction('destroy', this.removed);
867        }
868
869        // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
870        var rs = [].concat(this.getModifiedRecords());
871        if (!rs.length) { // Bail-out if empty...
872            return true;
873        }
874
875        // CREATE:  Next check for phantoms within rs.  splice-off and execute create.
876        var phantoms = [];
877        for (var i = rs.length-1; i >= 0; i--) {
878            if (rs[i].phantom === true) {
879                var rec = rs.splice(i, 1).shift();
880                if (rec.isValid()) {
881                    phantoms.push(rec);
882                }
883            } else if (!rs[i].isValid()) { // <-- while we're here, splice-off any !isValid real records
884                rs.splice(i,1);
885            }
886        }
887        // If we have valid phantoms, create them...
888        if (phantoms.length) {
889            this.doTransaction('create', phantoms);
890        }
891
892        // UPDATE:  And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
893        if (rs.length) {
894            this.doTransaction('update', rs);
895        }
896        return true;
897    },
898
899    // private.  Simply wraps call to Store#execute in try/catch.  Defers to Store#handleException on error.  Loops if batch: false
900    doTransaction : function(action, rs) {
901        function transaction(records) {
902            try {
903                this.execute(action, records);
904            } catch (e) {
905                this.handleException(e);
906            }
907        }
908        if (this.batch === false) {
909            for (var i = 0, len = rs.length; i < len; i++) {
910                transaction.call(this, rs[i]);
911            }
912        } else {
913            transaction.call(this, rs);
914        }
915    },
916
917    // @private callback-handler for remote CRUD actions
918    // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
919    createCallback : function(action, rs) {
920        var actions = Ext.data.Api.actions;
921        return (action == 'read') ? this.loadRecords : function(data, response, success) {
922            // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
923            this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, data);
924            // If success === false here, exception will have been called in DataProxy
925            if (success === true) {
926                this.fireEvent('write', this, action, data, response, rs);
927            }
928        };
929    },
930
931    // Clears records from modified array after an exception event.
932    // NOTE:  records are left marked dirty.  Do we want to commit them even though they were not updated/realized?
933    clearModified : function(rs) {
934        if (Ext.isArray(rs)) {
935            for (var n=rs.length-1;n>=0;n--) {
936                this.modified.splice(this.modified.indexOf(rs[n]), 1);
937            }
938        } else {
939            this.modified.splice(this.modified.indexOf(rs), 1);
940        }
941    },
942
943    // remap record ids in MixedCollection after records have been realized.  @see Store#onCreateRecords, @see DataReader#realize
944    reMap : function(record) {
945        if (Ext.isArray(record)) {
946            for (var i = 0, len = record.length; i < len; i++) {
947                this.reMap(record[i]);
948            }
949        } else {
950            delete this.data.map[record._phid];
951            this.data.map[record.id] = record;
952            var index = this.data.keys.indexOf(record._phid);
953            this.data.keys.splice(index, 1, record.id);
954            delete record._phid;
955        }
956    },
957
958    // @protected onCreateRecord proxy callback for create action
959    onCreateRecords : function(success, rs, data) {
960        if (success === true) {
961            try {
962                this.reader.realize(rs, data);
963                this.reMap(rs);
964            }
965            catch (e) {
966                this.handleException(e);
967                if (Ext.isArray(rs)) {
968                    // Recurse to run back into the try {}.  DataReader#realize splices-off the rs until empty.
969                    this.onCreateRecords(success, rs, data);
970                }
971            }
972        }
973    },
974
975    // @protected, onUpdateRecords proxy callback for update action
976    onUpdateRecords : function(success, rs, data) {
977        if (success === true) {
978            try {
979                this.reader.update(rs, data);
980            } catch (e) {
981                this.handleException(e);
982                if (Ext.isArray(rs)) {
983                    // Recurse to run back into the try {}.  DataReader#update splices-off the rs until empty.
984                    this.onUpdateRecords(success, rs, data);
985                }
986            }
987        }
988    },
989
990    // @protected onDestroyRecords proxy callback for destroy action
991    onDestroyRecords : function(success, rs, data) {
992        // splice each rec out of this.removed
993        rs = (rs instanceof Ext.data.Record) ? [rs] : rs;
994        for (var i=0,len=rs.length;i<len;i++) {
995            this.removed.splice(this.removed.indexOf(rs[i]), 1);
996        }
997        if (success === false) {
998            // put records back into store if remote destroy fails.
999            // @TODO: Might want to let developer decide.
1000            for (i=rs.length-1;i>=0;i--) {
1001                this.insert(rs[i].lastIndex, rs[i]);    // <-- lastIndex set in Store#destroyRecord
1002            }
1003        }
1004    },
1005
1006    // protected handleException.  Possibly temporary until Ext framework has an exception-handler.
1007    handleException : function(e) {
1008        // @see core/Error.js
1009        Ext.handleError(e);
1010    },
1011
1012    /**
1013     * <p>Reloads the Record cache from the configured Proxy using the configured {@link Ext.data.Reader Reader} and
1014     * the options from the last load operation performed.</p>
1015     * <p><b>Note</b>: see the Important note in {@link #load}.</p>
1016     * @param {Object} options (optional) An <tt>Object</tt> containing {@link #load loading options} which may
1017     * override the options used in the last {@link #load} operation. See {@link #load} for details (defaults to
1018     * <tt>null</tt>, in which case the {@link #lastOptions} are used).
1019     */
1020    reload : function(options){
1021        this.load(Ext.applyIf(options||{}, this.lastOptions));
1022    },
1023
1024    // private
1025    // Called as a callback by the Reader during a load operation.
1026    loadRecords : function(o, options, success){
1027        if(!o || success === false){
1028            if(success !== false){
1029                this.fireEvent('load', this, [], options);
1030            }
1031            if(options.callback){
1032                options.callback.call(options.scope || this, [], options, false, o);
1033            }
1034            return;
1035        }
1036        var r = o.records, t = o.totalRecords || r.length;
1037        if(!options || options.add !== true){
1038            if(this.pruneModifiedRecords){
1039                this.modified = [];
1040            }
1041            for(var i = 0, len = r.length; i < len; i++){
1042                r[i].join(this);
1043            }
1044            if(this.snapshot){
1045                this.data = this.snapshot;
1046                delete this.snapshot;
1047            }
1048            this.data.clear();
1049            this.data.addAll(r);
1050            this.totalLength = t;
1051            this.applySort();
1052            this.fireEvent('datachanged', this);
1053        }else{
1054            this.totalLength = Math.max(t, this.data.length+r.length);
1055            this.add(r);
1056        }
1057        this.fireEvent('load', this, r, options);
1058        if(options.callback){
1059            options.callback.call(options.scope || this, r, options, true);
1060        }
1061    },
1062
1063    /**
1064     * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
1065     * which understands the format of the data must have been configured in the constructor.
1066     * @param {Object} data The data block from which to read the Records.  The format of the data expected
1067     * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
1068     * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
1069     * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
1070     * the existing cache.
1071     * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
1072     * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
1073     * new, unique ids will be added.
1074     */
1075    loadData : function(o, append){
1076        var r = this.reader.readRecords(o);
1077        this.loadRecords(r, {add: append}, true);
1078    },
1079
1080    /**
1081     * Gets the number of cached records.
1082     * <p>If using paging, this may not be the total size of the dataset. If the data object
1083     * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1084     * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
1085     * @return {Number} The number of Records in the Store's cache.
1086     */
1087    getCount : function(){
1088        return this.data.length || 0;
1089    },
1090
1091    /**
1092     * Gets the total number of records in the dataset as returned by the server.
1093     * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
1094     * must contain the dataset size. For remote data sources, the value for this property
1095     * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
1096     * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
1097     * <b>Note</b>: see the Important note in {@link #load}.</p>
1098     * @return {Number} The number of Records as specified in the data object passed to the Reader
1099     * by the Proxy.
1100     * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
1101     */
1102    getTotalCount : function(){
1103        return this.totalLength || 0;
1104    },
1105
1106    /**
1107     * Returns an object describing the current sort state of this Store.
1108     * @return {Object} The sort state of the Store. An object with two properties:<ul>
1109     * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
1110     * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
1111     * </ul>
1112     * See <tt>{@link #sortInfo}</tt> for additional details.
1113     */
1114    getSortState : function(){
1115        return this.sortInfo;
1116    },
1117
1118    // private
1119    applySort : function(){
1120        if(this.sortInfo && !this.remoteSort){
1121            var s = this.sortInfo, f = s.field;
1122            this.sortData(f, s.direction);
1123        }
1124    },
1125
1126    // private
1127    sortData : function(f, direction){
1128        direction = direction || 'ASC';
1129        var st = this.fields.get(f).sortType;
1130        var fn = function(r1, r2){
1131            var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
1132            return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
1133        };
1134        this.data.sort(direction, fn);
1135        if(this.snapshot && this.snapshot != this.data){
1136            this.snapshot.sort(direction, fn);
1137        }
1138    },
1139
1140    /**
1141     * Sets the default sort column and order to be used by the next {@link #load} operation.
1142     * @param {String} fieldName The name of the field to sort by.
1143     * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1144     */
1145    setDefaultSort : function(field, dir){
1146        dir = dir ? dir.toUpperCase() : 'ASC';
1147        this.sortInfo = {field: field, direction: dir};
1148        this.sortToggle[field] = dir;
1149    },
1150
1151    /**
1152     * Sort the Records.
1153     * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
1154     * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
1155     * @param {String} fieldName The name of the field to sort by.
1156     * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
1157     */
1158    sort : function(fieldName, dir){
1159        var f = this.fields.get(fieldName);
1160        if(!f){
1161            return false;
1162        }
1163        if(!dir){
1164            if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
1165                dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
1166            }else{
1167                dir = f.sortDir;
1168            }
1169        }
1170        var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
1171        var si = (this.sortInfo) ? this.sortInfo : null;
1172
1173        this.sortToggle[f.name] = dir;
1174        this.sortInfo = {field: f.name, direction: dir};
1175        if(!this.remoteSort){
1176            this.applySort();
1177            this.fireEvent('datachanged', this);
1178        }else{
1179            if (!this.load(this.lastOptions)) {
1180                if (st) {
1181                    this.sortToggle[f.name] = st;
1182                }
1183                if (si) {
1184                    this.sortInfo = si;
1185                }
1186            }
1187        }
1188    },
1189
1190    /**
1191     * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
1192     * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
1193     * Returning <tt>false</tt> aborts and exits the iteration.
1194     * @param {Object} scope (optional) The scope in which to call the function (defaults to the {@link Ext.data.Record Record}).
1195     */
1196    each : function(fn, scope){
1197        this.data.each(fn, scope);
1198    },
1199
1200    /**
1201     * Gets all {@link Ext.data.Record records} modified since the last commit.  Modified records are
1202     * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
1203     * included.  See also <tt>{@link #pruneModifiedRecords}</tt> and
1204     * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
1205     * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
1206     * modifications.  To obtain modified fields within a modified record see
1207     *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
1208     */
1209    getModifiedRecords : function(){
1210        return this.modified;
1211    },
1212
1213    // private
1214    createFilterFn : function(property, value, anyMatch, caseSensitive){
1215        if(Ext.isEmpty(value, false)){
1216            return false;
1217        }
1218        value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
1219        return function(r){
1220            return value.test(r.data[property]);
1221        };
1222    },
1223
1224    /**
1225     * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
1226     * and <tt>end</tt> and returns the result.
1227     * @param {String} property A field in each record
1228     * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
1229     * @param {Number} end (optional) The last record index to include (defaults to length - 1)
1230     * @return {Number} The sum
1231     */
1232    sum : function(property, start, end){
1233        var rs = this.data.items, v = 0;
1234        start = start || 0;
1235        end = (end || end === 0) ? end : rs.length-1;
1236
1237        for(var i = start; i <= end; i++){
1238            v += (rs[i].data[property] || 0);
1239        }
1240        return v;
1241    },
1242
1243    /**
1244     * Filter the {@link Ext.data.Record records} by a specified property.
1245     * @param {String} field A field on your records
1246     * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
1247     * against the field.
1248     * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
1249     * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
1250     */
1251    filter : function(property, value, anyMatch, caseSensitive){
1252        var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1253        return fn ? this.filterBy(fn) : this.clearFilter();
1254    },
1255
1256    /**
1257     * Filter by a function. The specified function will be called for each
1258     * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1259     * otherwise it is filtered out.
1260     * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1261     * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1262     * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1263     * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1264     * </ul>
1265     * @param {Object} scope (optional) The scope of the function (defaults to this)
1266     */
1267    filterBy : function(fn, scope){
1268        this.snapshot = this.snapshot || this.data;
1269        this.data = this.queryBy(fn, scope||this);
1270        this.fireEvent('datachanged', this);
1271    },
1272
1273    /**
1274     * Query the records by a specified property.
1275     * @param {String} field A field on your records
1276     * @param {String/RegExp} value Either a string that the field
1277     * should begin with, or a RegExp to test against the field.
1278     * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
1279     * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1280     * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1281     */
1282    query : function(property, value, anyMatch, caseSensitive){
1283        var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1284        return fn ? this.queryBy(fn) : this.data.clone();
1285    },
1286
1287    /**
1288     * Query the cached records in this Store using a filtering function. The specified function
1289     * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1290     * included in the results.
1291     * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1292     * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1293     * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1294     * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1295     * </ul>
1296     * @param {Object} scope (optional) The scope of the function (defaults to this)
1297     * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1298     **/
1299    queryBy : function(fn, scope){
1300        var data = this.snapshot || this.data;
1301        return data.filterBy(fn, scope||this);
1302    },
1303
1304    /**
1305     * Finds the index of the first matching record in this store by a specific property/value.
1306     * @param {String} property A property on your objects
1307     * @param {String/RegExp} value Either a string that the property value
1308     * should begin with, or a RegExp to test against the property.
1309     * @param {Number} startIndex (optional) The index to start searching at
1310     * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1311     * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1312     * @return {Number} The matched index or -1
1313     */
1314    find : function(property, value, start, anyMatch, caseSensitive){
1315        var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
1316        return fn ? this.data.findIndexBy(fn, null, start) : -1;
1317    },
1318
1319    /**
1320     * Finds the index of the first matching record in this store by a specific property/value.
1321     * @param {String} property A property on your objects
1322     * @param {String/RegExp} value The value to match against
1323     * @param {Number} startIndex (optional) The index to start searching at
1324     * @return {Number} The matched index or -1
1325     */
1326    findExact: function(property, value, start){
1327        return this.data.findIndexBy(function(rec){
1328            return rec.get(property) === value;
1329        }, this, start);
1330    },
1331
1332    /**
1333     * Find the index of the first matching Record in this Store by a function.
1334     * If the function returns <tt>true</tt> it is considered a match.
1335     * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1336     * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
1337     * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
1338     * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1339     * </ul>
1340     * @param {Object} scope (optional) The scope of the function (defaults to this)
1341     * @param {Number} startIndex (optional) The index to start searching at
1342     * @return {Number} The matched index or -1
1343     */
1344    findBy : function(fn, scope, start){
1345        return this.data.findIndexBy(fn, scope, start);
1346    },
1347
1348    /**
1349     * Collects unique values for a particular dataIndex from this store.
1350     * @param {String} dataIndex The property to collect
1351     * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1352     * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1353     * @return {Array} An array of the unique values
1354     **/
1355    collect : function(dataIndex, allowNull, bypassFilter){
1356        var d = (bypassFilter === true && this.snapshot) ?
1357                this.snapshot.items : this.data.items;
1358        var v, sv, r = [], l = {};
1359        for(var i = 0, len = d.length; i < len; i++){
1360            v = d[i].data[dataIndex];
1361            sv = String(v);
1362            if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
1363                l[sv] = true;
1364                r[r.length] = v;
1365            }
1366        }
1367        return r;
1368    },
1369
1370    /**
1371     * Revert to a view of the Record cache with no filtering applied.
1372     * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1373     * {@link #datachanged} event.
1374     */
1375    clearFilter : function(suppressEvent){
1376        if(this.isFiltered()){
1377            this.data = this.snapshot;
1378            delete this.snapshot;
1379            if(suppressEvent !== true){
1380                this.fireEvent('datachanged', this);
1381            }
1382        }
1383    },
1384
1385    /**
1386     * Returns true if this store is currently filtered
1387     * @return {Boolean}
1388     */
1389    isFiltered : function(){
1390        return this.snapshot && this.snapshot != this.data;
1391    },
1392
1393    // private
1394    afterEdit : function(record){
1395        if(this.modified.indexOf(record) == -1){
1396            this.modified.push(record);
1397        }
1398        this.fireEvent('update', this, record, Ext.data.Record.EDIT);
1399    },
1400
1401    // private
1402    afterReject : function(record){
1403        this.modified.remove(record);
1404        this.fireEvent('update', this, record, Ext.data.Record.REJECT);
1405    },
1406
1407    // private
1408    afterCommit : function(record){
1409        this.modified.remove(record);
1410        this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
1411    },
1412
1413    /**
1414     * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
1415     * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
1416     * Ext.data.Record.COMMIT.
1417     */
1418    commitChanges : function(){
1419        var m = this.modified.slice(0);
1420        this.modified = [];
1421        for(var i = 0, len = m.length; i < len; i++){
1422            m[i].commit();
1423        }
1424    },
1425
1426    /**
1427     * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
1428     */
1429    rejectChanges : function(){
1430        var m = this.modified.slice(0);
1431        this.modified = [];
1432        for(var i = 0, len = m.length; i < len; i++){
1433            m[i].reject();
1434        }
1435    },
1436
1437    // private
1438    onMetaChange : function(meta, rtype, o){
1439        this.recordType = rtype;
1440        this.fields = rtype.prototype.fields;
1441        delete this.snapshot;
1442        if(meta.sortInfo){
1443            this.sortInfo = meta.sortInfo;
1444        }else if(this.sortInfo  && !this.fields.get(this.sortInfo.field)){
1445            delete this.sortInfo;
1446        }
1447        this.modified = [];
1448        this.fireEvent('metachange', this, this.reader.meta);
1449    },
1450
1451    // private
1452    findInsertIndex : function(record){
1453        this.suspendEvents();
1454        var data = this.data.clone();
1455        this.data.add(record);
1456        this.applySort();
1457        var index = this.data.indexOf(record);
1458        this.data = data;
1459        this.resumeEvents();
1460        return index;
1461    },
1462
1463    /**
1464     * Set the value for a property name in this store's {@link #baseParams}.  Usage:</p><pre><code>
1465myStore.setBaseParam('foo', {bar:3});
1466</code></pre>
1467     * @param {String} name Name of the property to assign
1468     * @param {Mixed} value Value to assign the <tt>name</tt>d property
1469     **/
1470    setBaseParam : function (name, value){
1471        this.baseParams = this.baseParams || {};
1472        this.baseParams[name] = value;
1473    }
1474});
1475
1476Ext.reg('store', Ext.data.Store);
1477
1478/**
1479 * @class Ext.data.Store.Error
1480 * @extends Ext.Error
1481 * Store Error extension.
1482 * @param {String} name
1483 */
1484Ext.data.Store.Error = Ext.extend(Ext.Error, {
1485    name: 'Ext.data.Store'
1486});
1487Ext.apply(Ext.data.Store.Error.prototype, {
1488    lang: {
1489        'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
1490    }
1491});
1492
Note: See TracBrowser for help on using the repository browser.