4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
15 * @class Roo.data.Store
16 * @extends Roo.util.Observable
17 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
18 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
20 * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
21 * has no knowledge of the format of the data returned by the Proxy.<br>
23 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
24 * instances from the data object. These records are cached and made available through accessor functions.
26 * Creates a new Store.
27 * @param {Object} config A config object containing the objects needed for the Store to access data,
28 * and read the data into Records.
30 Roo.data.Store = function(config){
31 this.data = new Roo.util.MixedCollection(false);
32 this.data.getKey = function(o){
44 if(config && config.data){
45 this.inlineData = config.data;
49 Roo.apply(this, config);
51 if(this.reader){ // reader passed
52 this.reader = Roo.factory(this.reader, Roo.data);
53 this.reader.xmodule = this.xmodule || false;
55 this.recordType = this.reader.recordType;
57 if(this.reader.onMetaChange){
58 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
63 this.fields = this.recordType.prototype.fields;
70 * Fires when the data cache has changed, and a widget which is using this Store
71 * as a Record cache should refresh its view.
77 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
79 * @param {Object} meta The JSON metadata
84 * Fires when Records have been added to the Store
86 * @param {Roo.data.Record[]} records The array of Records added
87 * @param {Number} index The index at which the record(s) were added
92 * Fires when a Record has been removed from the Store
94 * @param {Roo.data.Record} record The Record that was removed
95 * @param {Number} index The index at which the record was removed
100 * Fires when a Record has been updated
101 * @param {Store} this
102 * @param {Roo.data.Record} record The Record that was updated
103 * @param {String} operation The update operation being performed. Value may be one of:
106 Roo.data.Record.REJECT
107 Roo.data.Record.COMMIT
113 * Fires when the data cache has been cleared.
114 * @param {Store} this
119 * Fires before a request is made for a new data object. If the beforeload handler returns false
120 * the load action will be canceled.
121 * @param {Store} this
122 * @param {Object} options The loading options that were specified (see {@link #load} for details)
127 * Fires after a new set of Records has been loaded.
128 * @param {Store} this
129 * @param {Roo.data.Record[]} records The Records that were loaded
130 * @param {Object} options The loading options that were specified (see {@link #load} for details)
134 * @event loadexception
135 * Fires if an exception occurs in the Proxy during loading.
136 * Called with the signature of the Proxy's "loadexception" event.
137 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
140 * @param {Object} return from JsonData.reader() - success, totalRecords, records
141 * @param {Object} load options
142 * @param {Object} jsonData from your request (normally this contains the Exception)
148 this.proxy = Roo.factory(this.proxy, Roo.data);
149 this.proxy.xmodule = this.xmodule || false;
150 this.relayEvents(this.proxy, ["loadexception"]);
152 this.sortToggle = {};
154 Roo.data.Store.superclass.constructor.call(this);
157 this.loadData(this.inlineData);
158 delete this.inlineData;
161 Roo.extend(Roo.data.Store, Roo.util.Observable, {
163 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
164 * without a remote query - used by combo/forms at present.
168 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
171 * @cfg {Array} data Inline data to be loaded when the store is initialized.
174 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
175 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
178 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
179 * on any HTTP request
182 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
185 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
186 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
191 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
192 * loaded or when a record is removed. (defaults to false).
194 pruneModifiedRecords : false,
200 * Add Records to the Store and fires the add event.
201 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
203 add : function(records){
204 records = [].concat(records);
205 for(var i = 0, len = records.length; i < len; i++){
206 records[i].join(this);
208 var index = this.data.length;
209 this.data.addAll(records);
210 this.fireEvent("add", this, records, index);
214 * Remove a Record from the Store and fires the remove event.
215 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
217 remove : function(record){
218 var index = this.data.indexOf(record);
219 this.data.removeAt(index);
220 if(this.pruneModifiedRecords){
221 this.modified.remove(record);
223 this.fireEvent("remove", this, record, index);
227 * Remove all Records from the Store and fires the clear event.
229 removeAll : function(){
231 if(this.pruneModifiedRecords){
234 this.fireEvent("clear", this);
238 * Inserts Records to the Store at the given index and fires the add event.
239 * @param {Number} index The start index at which to insert the passed Records.
240 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
242 insert : function(index, records){
243 records = [].concat(records);
244 for(var i = 0, len = records.length; i < len; i++){
245 this.data.insert(index, records[i]);
246 records[i].join(this);
248 this.fireEvent("add", this, records, index);
252 * Get the index within the cache of the passed Record.
253 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
254 * @return {Number} The index of the passed Record. Returns -1 if not found.
256 indexOf : function(record){
257 return this.data.indexOf(record);
261 * Get the index within the cache of the Record with the passed id.
262 * @param {String} id The id of the Record to find.
263 * @return {Number} The index of the Record. Returns -1 if not found.
265 indexOfId : function(id){
266 return this.data.indexOfKey(id);
270 * Get the Record with the specified id.
271 * @param {String} id The id of the Record to find.
272 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
274 getById : function(id){
275 return this.data.key(id);
279 * Get the Record at the specified index.
280 * @param {Number} index The index of the Record to find.
281 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
283 getAt : function(index){
284 return this.data.itemAt(index);
288 * Returns a range of Records between specified indices.
289 * @param {Number} startIndex (optional) The starting index (defaults to 0)
290 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
291 * @return {Roo.data.Record[]} An array of Records
293 getRange : function(start, end){
294 return this.data.getRange(start, end);
298 storeOptions : function(o){
299 o = Roo.apply({}, o);
302 this.lastOptions = o;
306 * Loads the Record cache from the configured Proxy using the configured Reader.
308 * If using remote paging, then the first load call must specify the <em>start</em>
309 * and <em>limit</em> properties in the options.params property to establish the initial
310 * position within the dataset, and the number of Records to cache on each read from the Proxy.
312 * <strong>It is important to note that for remote data sources, loading is asynchronous,
313 * and this call will return before the new data has been loaded. Perform any post-processing
314 * in a callback function, or in a "load" event handler.</strong>
316 * @param {Object} options An object containing properties which control loading options:<ul>
317 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
318 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
319 * passed the following arguments:<ul>
320 * <li>r : Roo.data.Record[]</li>
321 * <li>options: Options object from the load call</li>
322 * <li>success: Boolean success indicator</li></ul></li>
323 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
324 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
327 load : function(options){
328 options = options || {};
329 if(this.fireEvent("beforeload", this, options) !== false){
330 this.storeOptions(options);
331 var p = Roo.apply(options.params || {}, this.baseParams);
332 // if meta was not loaded from remote source.. try requesting it.
333 if (!this.reader.metaFromRemote) {
336 if(this.sortInfo && this.remoteSort){
337 var pn = this.paramNames;
338 p[pn["sort"]] = this.sortInfo.field;
339 p[pn["dir"]] = this.sortInfo.direction;
341 this.proxy.load(p, this.reader, this.loadRecords, this, options);
346 * Reloads the Record cache from the configured Proxy using the configured Reader and
347 * the options from the last load operation performed.
348 * @param {Object} options (optional) An object containing properties which may override the options
349 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
350 * the most recently used options are reused).
352 reload : function(options){
353 this.load(Roo.applyIf(options||{}, this.lastOptions));
357 // Called as a callback by the Reader during a load operation.
358 loadRecords : function(o, options, success){
359 if(!o || success === false){
360 if(success !== false){
361 this.fireEvent("load", this, [], options);
363 if(options.callback){
364 options.callback.call(options.scope || this, [], options, false);
368 // if data returned failure - throw an exception.
369 if (o.success === false) {
370 this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
373 var r = o.records, t = o.totalRecords || r.length;
374 if(!options || options.add !== true){
375 if(this.pruneModifiedRecords){
378 for(var i = 0, len = r.length; i < len; i++){
382 this.data = this.snapshot;
383 delete this.snapshot;
387 this.totalLength = t;
389 this.fireEvent("datachanged", this);
391 this.totalLength = Math.max(t, this.data.length+r.length);
394 this.fireEvent("load", this, r, options);
395 if(options.callback){
396 options.callback.call(options.scope || this, r, options, true);
401 * Loads data from a passed data block. A Reader which understands the format of the data
402 * must have been configured in the constructor.
403 * @param {Object} data The data block from which to read the Records. The format of the data expected
404 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
405 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
407 loadData : function(o, append){
408 var r = this.reader.readRecords(o);
409 this.loadRecords(r, {add: append}, true);
413 * Gets the number of cached records.
415 * <em>If using paging, this may not be the total size of the dataset. If the data object
416 * used by the Reader contains the dataset size, then the getTotalCount() function returns
417 * the data set size</em>
419 getCount : function(){
420 return this.data.length || 0;
424 * Gets the total number of records in the dataset as returned by the server.
426 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
427 * the dataset size</em>
429 getTotalCount : function(){
430 return this.totalLength || 0;
434 * Returns the sort state of the Store as an object with two properties:
436 field {String} The name of the field by which the Records are sorted
437 direction {String} The sort order, "ASC" or "DESC"
440 getSortState : function(){
441 return this.sortInfo;
445 applySort : function(){
446 if(this.sortInfo && !this.remoteSort){
447 var s = this.sortInfo, f = s.field;
448 var st = this.fields.get(f).sortType;
449 var fn = function(r1, r2){
450 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
451 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
453 this.data.sort(s.direction, fn);
454 if(this.snapshot && this.snapshot != this.data){
455 this.snapshot.sort(s.direction, fn);
461 * Sets the default sort column and order to be used by the next load operation.
462 * @param {String} fieldName The name of the field to sort by.
463 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
465 setDefaultSort : function(field, dir){
466 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
471 * If remote sorting is used, the sort is performed on the server, and the cache is
472 * reloaded. If local sorting is used, the cache is sorted internally.
473 * @param {String} fieldName The name of the field to sort by.
474 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
476 sort : function(fieldName, dir){
477 var f = this.fields.get(fieldName);
479 if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
480 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
485 this.sortToggle[f.name] = dir;
486 this.sortInfo = {field: f.name, direction: dir};
487 if(!this.remoteSort){
489 this.fireEvent("datachanged", this);
491 this.load(this.lastOptions);
496 * Calls the specified function for each of the Records in the cache.
497 * @param {Function} fn The function to call. The Record is passed as the first parameter.
498 * Returning <em>false</em> aborts and exits the iteration.
499 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
501 each : function(fn, scope){
502 this.data.each(fn, scope);
506 * Gets all records modified since the last commit. Modified records are persisted across load operations
507 * (e.g., during paging).
508 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
510 getModifiedRecords : function(){
511 return this.modified;
515 createFilterFn : function(property, value, anyMatch){
516 if(!value.exec){ // not a regex
517 value = String(value);
518 if(value.length == 0){
521 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
524 return value.test(r.data[property]);
529 * Sums the value of <i>property</i> for each record between start and end and returns the result.
530 * @param {String} property A field on your records
531 * @param {Number} start The record index to start at (defaults to 0)
532 * @param {Number} end The last record index to include (defaults to length - 1)
533 * @return {Number} The sum
535 sum : function(property, start, end){
536 var rs = this.data.items, v = 0;
538 end = (end || end === 0) ? end : rs.length-1;
540 for(var i = start; i <= end; i++){
541 v += (rs[i].data[property] || 0);
547 * Filter the records by a specified property.
548 * @param {String} field A field on your records
549 * @param {String/RegExp} value Either a string that the field
550 * should start with or a RegExp to test against the field
551 * @param {Boolean} anyMatch True to match any part not just the beginning
553 filter : function(property, value, anyMatch){
554 var fn = this.createFilterFn(property, value, anyMatch);
555 return fn ? this.filterBy(fn) : this.clearFilter();
559 * Filter by a function. The specified function will be called with each
560 * record in this data source. If the function returns true the record is included,
561 * otherwise it is filtered.
562 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
563 * @param {Object} scope (optional) The scope of the function (defaults to this)
565 filterBy : function(fn, scope){
566 this.snapshot = this.snapshot || this.data;
567 this.data = this.queryBy(fn, scope||this);
568 this.fireEvent("datachanged", this);
572 * Query the records by a specified property.
573 * @param {String} field A field on your records
574 * @param {String/RegExp} value Either a string that the field
575 * should start with or a RegExp to test against the field
576 * @param {Boolean} anyMatch True to match any part not just the beginning
577 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
579 query : function(property, value, anyMatch){
580 var fn = this.createFilterFn(property, value, anyMatch);
581 return fn ? this.queryBy(fn) : this.data.clone();
585 * Query by a function. The specified function will be called with each
586 * record in this data source. If the function returns true the record is included
588 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
589 * @param {Object} scope (optional) The scope of the function (defaults to this)
590 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
592 queryBy : function(fn, scope){
593 var data = this.snapshot || this.data;
594 return data.filterBy(fn, scope||this);
598 * Collects unique values for a particular dataIndex from this store.
599 * @param {String} dataIndex The property to collect
600 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
601 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
602 * @return {Array} An array of the unique values
604 collect : function(dataIndex, allowNull, bypassFilter){
605 var d = (bypassFilter === true && this.snapshot) ?
606 this.snapshot.items : this.data.items;
607 var v, sv, r = [], l = {};
608 for(var i = 0, len = d.length; i < len; i++){
609 v = d[i].data[dataIndex];
611 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
620 * Revert to a view of the Record cache with no filtering applied.
621 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
623 clearFilter : function(suppressEvent){
624 if(this.snapshot && this.snapshot != this.data){
625 this.data = this.snapshot;
626 delete this.snapshot;
627 if(suppressEvent !== true){
628 this.fireEvent("datachanged", this);
634 afterEdit : function(record){
635 if(this.modified.indexOf(record) == -1){
636 this.modified.push(record);
638 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
642 afterReject : function(record){
643 this.modified.remove(record);
644 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
648 afterCommit : function(record){
649 this.modified.remove(record);
650 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
654 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
655 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
657 commitChanges : function(){
658 var m = this.modified.slice(0);
660 for(var i = 0, len = m.length; i < len; i++){
666 * Cancel outstanding changes on all changed records.
668 rejectChanges : function(){
669 var m = this.modified.slice(0);
671 for(var i = 0, len = m.length; i < len; i++){
676 onMetaChange : function(meta, rtype, o){
677 this.recordType = rtype;
678 this.fields = rtype.prototype.fields;
679 delete this.snapshot;
680 this.sortInfo = meta.sortInfo || this.sortInfo;
682 this.fireEvent('metachange', this, this.reader.meta);