~cdparra/gelee/trunk

« back to all changes in this revision

Viewing changes to webui/extjs/source/data/Store.js

  • Committer: parra
  • Date: 2010-03-15 15:56:56 UTC
  • Revision ID: svn-v4:ac5bba68-f036-4e09-846e-8f32731cc928:trunk/gelee:1448
merged gelee at svn

Show diffs side-by-side

added added

removed removed

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