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){
42 "multisort" : "_multisort"
45 if(config && config.data){
46 this.inlineData = config.data;
50 Roo.apply(this, config);
52 if(this.reader){ // reader passed
53 this.reader = Roo.factory(this.reader, Roo.data);
54 this.reader.xmodule = this.xmodule || false;
56 this.recordType = this.reader.recordType;
58 if(this.reader.onMetaChange){
59 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
64 this.fields = this.recordType.prototype.fields;
71 * Fires when the data cache has changed, and a widget which is using this Store
72 * as a Record cache should refresh its view.
78 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
80 * @param {Object} meta The JSON metadata
85 * Fires when Records have been added to the Store
87 * @param {Roo.data.Record[]} records The array of Records added
88 * @param {Number} index The index at which the record(s) were added
93 * Fires when a Record has been removed from the Store
95 * @param {Roo.data.Record} record The Record that was removed
96 * @param {Number} index The index at which the record was removed
101 * Fires when a Record has been updated
102 * @param {Store} this
103 * @param {Roo.data.Record} record The Record that was updated
104 * @param {String} operation The update operation being performed. Value may be one of:
107 Roo.data.Record.REJECT
108 Roo.data.Record.COMMIT
114 * Fires when the data cache has been cleared.
115 * @param {Store} this
120 * Fires before a request is made for a new data object. If the beforeload handler returns false
121 * the load action will be canceled.
122 * @param {Store} this
123 * @param {Object} options The loading options that were specified (see {@link #load} for details)
128 * Fires after a new set of Records has been loaded.
129 * @param {Store} this
130 * @param {Roo.data.Record[]} records The Records that were loaded
131 * @param {Object} options The loading options that were specified (see {@link #load} for details)
135 * @event loadexception
136 * Fires if an exception occurs in the Proxy during loading.
137 * Called with the signature of the Proxy's "loadexception" event.
138 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
141 * @param {Object} return from JsonData.reader() - success, totalRecords, records
142 * @param {Object} load options
143 * @param {Object} jsonData from your request (normally this contains the Exception)
149 this.proxy = Roo.factory(this.proxy, Roo.data);
150 this.proxy.xmodule = this.xmodule || false;
151 this.relayEvents(this.proxy, ["loadexception"]);
153 this.sortToggle = {};
154 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
156 Roo.data.Store.superclass.constructor.call(this);
159 this.loadData(this.inlineData);
160 delete this.inlineData;
163 Roo.extend(Roo.data.Store, Roo.util.Observable, {
165 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
166 * without a remote query - used by combo/forms at present.
170 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
173 * @cfg {Array} data Inline data to be loaded when the store is initialized.
176 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
177 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
180 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
181 * on any HTTP request
184 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
187 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
191 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
192 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
197 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
198 * loaded or when a record is removed. (defaults to false).
200 pruneModifiedRecords : false,
206 * Add Records to the Store and fires the add event.
207 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
209 add : function(records){
210 records = [].concat(records);
211 for(var i = 0, len = records.length; i < len; i++){
212 records[i].join(this);
214 var index = this.data.length;
215 this.data.addAll(records);
216 this.fireEvent("add", this, records, index);
220 * Remove a Record from the Store and fires the remove event.
221 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
223 remove : function(record){
224 var index = this.data.indexOf(record);
225 this.data.removeAt(index);
226 if(this.pruneModifiedRecords){
227 this.modified.remove(record);
229 this.fireEvent("remove", this, record, index);
233 * Remove all Records from the Store and fires the clear event.
235 removeAll : function(){
237 if(this.pruneModifiedRecords){
240 this.fireEvent("clear", this);
244 * Inserts Records to the Store at the given index and fires the add event.
245 * @param {Number} index The start index at which to insert the passed Records.
246 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
248 insert : function(index, records){
249 records = [].concat(records);
250 for(var i = 0, len = records.length; i < len; i++){
251 this.data.insert(index, records[i]);
252 records[i].join(this);
254 this.fireEvent("add", this, records, index);
258 * Get the index within the cache of the passed Record.
259 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
260 * @return {Number} The index of the passed Record. Returns -1 if not found.
262 indexOf : function(record){
263 return this.data.indexOf(record);
267 * Get the index within the cache of the Record with the passed id.
268 * @param {String} id The id of the Record to find.
269 * @return {Number} The index of the Record. Returns -1 if not found.
271 indexOfId : function(id){
272 return this.data.indexOfKey(id);
276 * Get the Record with the specified id.
277 * @param {String} id The id of the Record to find.
278 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
280 getById : function(id){
281 return this.data.key(id);
285 * Get the Record at the specified index.
286 * @param {Number} index The index of the Record to find.
287 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
289 getAt : function(index){
290 return this.data.itemAt(index);
294 * Returns a range of Records between specified indices.
295 * @param {Number} startIndex (optional) The starting index (defaults to 0)
296 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
297 * @return {Roo.data.Record[]} An array of Records
299 getRange : function(start, end){
300 return this.data.getRange(start, end);
304 storeOptions : function(o){
305 o = Roo.apply({}, o);
308 this.lastOptions = o;
312 * Loads the Record cache from the configured Proxy using the configured Reader.
314 * If using remote paging, then the first load call must specify the <em>start</em>
315 * and <em>limit</em> properties in the options.params property to establish the initial
316 * position within the dataset, and the number of Records to cache on each read from the Proxy.
318 * <strong>It is important to note that for remote data sources, loading is asynchronous,
319 * and this call will return before the new data has been loaded. Perform any post-processing
320 * in a callback function, or in a "load" event handler.</strong>
322 * @param {Object} options An object containing properties which control loading options:<ul>
323 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
324 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
325 * passed the following arguments:<ul>
326 * <li>r : Roo.data.Record[]</li>
327 * <li>options: Options object from the load call</li>
328 * <li>success: Boolean success indicator</li></ul></li>
329 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
330 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
333 load : function(options){
334 options = options || {};
335 if(this.fireEvent("beforeload", this, options) !== false){
336 this.storeOptions(options);
337 var p = Roo.apply(options.params || {}, this.baseParams);
338 // if meta was not loaded from remote source.. try requesting it.
339 if (!this.reader.metaFromRemote) {
342 if(this.sortInfo && this.remoteSort){
343 var pn = this.paramNames;
344 p[pn["sort"]] = this.sortInfo.field;
345 p[pn["dir"]] = this.sortInfo.direction;
347 if (this.multiSort) {
348 var pn = this.paramNames;
349 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
352 this.proxy.load(p, this.reader, this.loadRecords, this, options);
357 * Reloads the Record cache from the configured Proxy using the configured Reader and
358 * the options from the last load operation performed.
359 * @param {Object} options (optional) An object containing properties which may override the options
360 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
361 * the most recently used options are reused).
363 reload : function(options){
364 this.load(Roo.applyIf(options||{}, this.lastOptions));
368 // Called as a callback by the Reader during a load operation.
369 loadRecords : function(o, options, success){
370 if(!o || success === false){
371 if(success !== false){
372 this.fireEvent("load", this, [], options);
374 if(options.callback){
375 options.callback.call(options.scope || this, [], options, false);
379 // if data returned failure - throw an exception.
380 if (o.success === false) {
381 this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
384 var r = o.records, t = o.totalRecords || r.length;
385 if(!options || options.add !== true){
386 if(this.pruneModifiedRecords){
389 for(var i = 0, len = r.length; i < len; i++){
393 this.data = this.snapshot;
394 delete this.snapshot;
398 this.totalLength = t;
400 this.fireEvent("datachanged", this);
402 this.totalLength = Math.max(t, this.data.length+r.length);
405 this.fireEvent("load", this, r, options);
406 if(options.callback){
407 options.callback.call(options.scope || this, r, options, true);
412 * Loads data from a passed data block. A Reader which understands the format of the data
413 * must have been configured in the constructor.
414 * @param {Object} data The data block from which to read the Records. The format of the data expected
415 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
416 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
418 loadData : function(o, append){
419 var r = this.reader.readRecords(o);
420 this.loadRecords(r, {add: append}, true);
424 * Gets the number of cached records.
426 * <em>If using paging, this may not be the total size of the dataset. If the data object
427 * used by the Reader contains the dataset size, then the getTotalCount() function returns
428 * the data set size</em>
430 getCount : function(){
431 return this.data.length || 0;
435 * Gets the total number of records in the dataset as returned by the server.
437 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
438 * the dataset size</em>
440 getTotalCount : function(){
441 return this.totalLength || 0;
445 * Returns the sort state of the Store as an object with two properties:
447 field {String} The name of the field by which the Records are sorted
448 direction {String} The sort order, "ASC" or "DESC"
451 getSortState : function(){
452 return this.sortInfo;
456 applySort : function(){
457 if(this.sortInfo && !this.remoteSort){
458 var s = this.sortInfo, f = s.field;
459 var st = this.fields.get(f).sortType;
460 var fn = function(r1, r2){
461 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
462 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
464 this.data.sort(s.direction, fn);
465 if(this.snapshot && this.snapshot != this.data){
466 this.snapshot.sort(s.direction, fn);
472 * Sets the default sort column and order to be used by the next load operation.
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 setDefaultSort : function(field, dir){
477 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
482 * If remote sorting is used, the sort is performed on the server, and the cache is
483 * reloaded. If local sorting is used, the cache is sorted internally.
484 * @param {String} fieldName The name of the field to sort by.
485 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
487 sort : function(fieldName, dir){
488 var f = this.fields.get(fieldName);
490 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
492 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
493 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
498 this.sortToggle[f.name] = dir;
499 this.sortInfo = {field: f.name, direction: dir};
500 if(!this.remoteSort){
502 this.fireEvent("datachanged", this);
504 this.load(this.lastOptions);
509 * Calls the specified function for each of the Records in the cache.
510 * @param {Function} fn The function to call. The Record is passed as the first parameter.
511 * Returning <em>false</em> aborts and exits the iteration.
512 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
514 each : function(fn, scope){
515 this.data.each(fn, scope);
519 * Gets all records modified since the last commit. Modified records are persisted across load operations
520 * (e.g., during paging).
521 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
523 getModifiedRecords : function(){
524 return this.modified;
528 createFilterFn : function(property, value, anyMatch){
529 if(!value.exec){ // not a regex
530 value = String(value);
531 if(value.length == 0){
534 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
537 return value.test(r.data[property]);
542 * Sums the value of <i>property</i> for each record between start and end and returns the result.
543 * @param {String} property A field on your records
544 * @param {Number} start The record index to start at (defaults to 0)
545 * @param {Number} end The last record index to include (defaults to length - 1)
546 * @return {Number} The sum
548 sum : function(property, start, end){
549 var rs = this.data.items, v = 0;
551 end = (end || end === 0) ? end : rs.length-1;
553 for(var i = start; i <= end; i++){
554 v += (rs[i].data[property] || 0);
560 * Filter the records by a specified property.
561 * @param {String} field A field on your records
562 * @param {String/RegExp} value Either a string that the field
563 * should start with or a RegExp to test against the field
564 * @param {Boolean} anyMatch True to match any part not just the beginning
566 filter : function(property, value, anyMatch){
567 var fn = this.createFilterFn(property, value, anyMatch);
568 return fn ? this.filterBy(fn) : this.clearFilter();
572 * Filter by a function. The specified function will be called with each
573 * record in this data source. If the function returns true the record is included,
574 * otherwise it is filtered.
575 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
576 * @param {Object} scope (optional) The scope of the function (defaults to this)
578 filterBy : function(fn, scope){
579 this.snapshot = this.snapshot || this.data;
580 this.data = this.queryBy(fn, scope||this);
581 this.fireEvent("datachanged", this);
585 * Query the records by a specified property.
586 * @param {String} field A field on your records
587 * @param {String/RegExp} value Either a string that the field
588 * should start with or a RegExp to test against the field
589 * @param {Boolean} anyMatch True to match any part not just the beginning
590 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
592 query : function(property, value, anyMatch){
593 var fn = this.createFilterFn(property, value, anyMatch);
594 return fn ? this.queryBy(fn) : this.data.clone();
598 * Query by a function. The specified function will be called with each
599 * record in this data source. If the function returns true the record is included
601 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
602 * @param {Object} scope (optional) The scope of the function (defaults to this)
603 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
605 queryBy : function(fn, scope){
606 var data = this.snapshot || this.data;
607 return data.filterBy(fn, scope||this);
611 * Collects unique values for a particular dataIndex from this store.
612 * @param {String} dataIndex The property to collect
613 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
614 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
615 * @return {Array} An array of the unique values
617 collect : function(dataIndex, allowNull, bypassFilter){
618 var d = (bypassFilter === true && this.snapshot) ?
619 this.snapshot.items : this.data.items;
620 var v, sv, r = [], l = {};
621 for(var i = 0, len = d.length; i < len; i++){
622 v = d[i].data[dataIndex];
624 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
633 * Revert to a view of the Record cache with no filtering applied.
634 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
636 clearFilter : function(suppressEvent){
637 if(this.snapshot && this.snapshot != this.data){
638 this.data = this.snapshot;
639 delete this.snapshot;
640 if(suppressEvent !== true){
641 this.fireEvent("datachanged", this);
647 afterEdit : function(record){
648 if(this.modified.indexOf(record) == -1){
649 this.modified.push(record);
651 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
655 afterReject : function(record){
656 this.modified.remove(record);
657 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
661 afterCommit : function(record){
662 this.modified.remove(record);
663 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
667 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
668 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
670 commitChanges : function(){
671 var m = this.modified.slice(0);
673 for(var i = 0, len = m.length; i < len; i++){
679 * Cancel outstanding changes on all changed records.
681 rejectChanges : function(){
682 var m = this.modified.slice(0);
684 for(var i = 0, len = m.length; i < len; i++){
689 onMetaChange : function(meta, rtype, o){
690 this.recordType = rtype;
691 this.fields = rtype.prototype.fields;
692 delete this.snapshot;
693 this.sortInfo = meta.sortInfo || this.sortInfo;
695 this.fireEvent('metachange', this, this.reader.meta);