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)
127 * @event beforeloadadd
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)
133 beforeloadadd : true,
136 * Fires after a new set of Records has been loaded, before they are added to the store.
137 * @param {Store} this
138 * @param {Roo.data.Record[]} records The Records that were loaded
139 * @param {Object} options The loading options that were specified (see {@link #load} for details)
140 * @params {Object} return from reader
144 * @event loadexception
145 * Fires if an exception occurs in the Proxy during loading.
146 * Called with the signature of the Proxy's "loadexception" event.
147 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
150 * @param {Object} return from JsonData.reader() - success, totalRecords, records
151 * @param {Object} load options
152 * @param {Object} jsonData from your request (normally this contains the Exception)
158 this.proxy = Roo.factory(this.proxy, Roo.data);
159 this.proxy.xmodule = this.xmodule || false;
160 this.relayEvents(this.proxy, ["loadexception"]);
162 this.sortToggle = {};
163 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
165 Roo.data.Store.superclass.constructor.call(this);
168 this.loadData(this.inlineData);
169 delete this.inlineData;
173 Roo.extend(Roo.data.Store, Roo.util.Observable, {
175 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
176 * without a remote query - used by combo/forms at present.
180 * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
183 * @cfg {Array} data Inline data to be loaded when the store is initialized.
186 * @cfg {Roo.data.DataReader} reader [required] The Reader object which processes the data object and returns
187 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
190 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
191 * on any HTTP request
194 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
197 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
201 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
202 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
207 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
208 * loaded or when a record is removed. (defaults to false).
210 pruneModifiedRecords : false,
216 * Add Records to the Store and fires the add event.
217 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
219 add : function(records){
220 records = [].concat(records);
221 for(var i = 0, len = records.length; i < len; i++){
222 records[i].join(this);
224 var index = this.data.length;
225 this.data.addAll(records);
226 this.fireEvent("add", this, records, index);
230 * Remove a Record from the Store and fires the remove event.
231 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
233 remove : function(record){
234 var index = this.data.indexOf(record);
235 this.data.removeAt(index);
237 if(this.pruneModifiedRecords){
238 this.modified.remove(record);
240 this.fireEvent("remove", this, record, index);
244 * Remove all Records from the Store and fires the clear event.
246 removeAll : function(){
248 if(this.pruneModifiedRecords){
251 this.fireEvent("clear", this);
255 * Inserts Records to the Store at the given index and fires the add event.
256 * @param {Number} index The start index at which to insert the passed Records.
257 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
259 insert : function(index, records){
260 records = [].concat(records);
261 for(var i = 0, len = records.length; i < len; i++){
262 this.data.insert(index, records[i]);
263 records[i].join(this);
265 this.fireEvent("add", this, records, index);
269 * Get the index within the cache of the passed Record.
270 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
271 * @return {Number} The index of the passed Record. Returns -1 if not found.
273 indexOf : function(record){
274 return this.data.indexOf(record);
278 * Get the index within the cache of the Record with the passed id.
279 * @param {String} id The id of the Record to find.
280 * @return {Number} The index of the Record. Returns -1 if not found.
282 indexOfId : function(id){
283 return this.data.indexOfKey(id);
287 * Get the Record with the specified id.
288 * @param {String} id The id of the Record to find.
289 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
291 getById : function(id){
292 return this.data.key(id);
296 * Get the Record at the specified index.
297 * @param {Number} index The index of the Record to find.
298 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
300 getAt : function(index){
301 return this.data.itemAt(index);
305 * Returns a range of Records between specified indices.
306 * @param {Number} startIndex (optional) The starting index (defaults to 0)
307 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
308 * @return {Roo.data.Record[]} An array of Records
310 getRange : function(start, end){
311 return this.data.getRange(start, end);
315 storeOptions : function(o){
316 o = Roo.apply({}, o);
319 this.lastOptions = o;
323 * Loads the Record cache from the configured Proxy using the configured Reader.
325 * If using remote paging, then the first load call must specify the <em>start</em>
326 * and <em>limit</em> properties in the options.params property to establish the initial
327 * position within the dataset, and the number of Records to cache on each read from the Proxy.
329 * <strong>It is important to note that for remote data sources, loading is asynchronous,
330 * and this call will return before the new data has been loaded. Perform any post-processing
331 * in a callback function, or in a "load" event handler.</strong>
333 * @param {Object} options An object containing properties which control loading options:<ul>
334 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
335 * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
338 data : data, // array of key=>value data like JsonReader
345 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
346 * passed the following arguments:<ul>
347 * <li>r : Roo.data.Record[]</li>
348 * <li>options: Options object from the load call</li>
349 * <li>success: Boolean success indicator</li></ul></li>
350 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
351 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
354 load : function(options){
355 options = options || {};
356 if(this.fireEvent("beforeload", this, options) !== false){
357 this.storeOptions(options);
358 var p = Roo.apply(options.params || {}, this.baseParams);
359 // if meta was not loaded from remote source.. try requesting it.
360 if (!this.reader.metaFromRemote) {
363 if(this.sortInfo && this.remoteSort){
364 var pn = this.paramNames;
365 p[pn["sort"]] = this.sortInfo.field;
366 p[pn["dir"]] = this.sortInfo.direction;
368 if (this.multiSort) {
369 var pn = this.paramNames;
370 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
373 this.proxy.load(p, this.reader, this.loadRecords, this, options);
378 * Reloads the Record cache from the configured Proxy using the configured Reader and
379 * the options from the last load operation performed.
380 * @param {Object} options (optional) An object containing properties which may override the options
381 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
382 * the most recently used options are reused).
384 reload : function(options){
385 this.load(Roo.applyIf(options||{}, this.lastOptions));
389 // Called as a callback by the Reader during a load operation.
390 loadRecords : function(o, options, success){
393 if(success !== false){
394 this.fireEvent("load", this, [], options, o);
396 if(options.callback){
397 options.callback.call(options.scope || this, [], options, false);
401 // if data returned failure - throw an exception.
402 if (o.success === false) {
403 // show a message if no listener is registered.
404 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
405 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
407 // loadmask wil be hooked into this..
408 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
411 var r = o.records, t = o.totalRecords || r.length;
413 this.fireEvent("beforeloadadd", this, r, options, o);
415 if(!options || options.add !== true){
416 if(this.pruneModifiedRecords){
419 for(var i = 0, len = r.length; i < len; i++){
423 this.data = this.snapshot;
424 delete this.snapshot;
428 this.totalLength = t;
430 this.fireEvent("datachanged", this);
432 this.totalLength = Math.max(t, this.data.length+r.length);
436 if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
438 var e = new Roo.data.Record({});
440 e.set(this.parent.displayField, this.parent.emptyTitle);
441 e.set(this.parent.valueField, '');
446 this.fireEvent("load", this, r, options, o);
447 if(options.callback){
448 options.callback.call(options.scope || this, r, options, true);
454 * Loads data from a passed data block. A Reader which understands the format of the data
455 * must have been configured in the constructor.
456 * @param {Object} data The data block from which to read the Records. The format of the data expected
457 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
458 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
460 loadData : function(o, append){
461 var r = this.reader.readRecords(o);
462 this.loadRecords(r, {add: append}, true);
466 * using 'cn' the nested child reader read the child array into it's child stores.
467 * @param {Object} rec The record with a 'children array
469 loadDataFromChildren : function(rec)
471 this.loadData(this.reader.toLoadData(rec));
476 * Gets the number of cached records.
478 * <em>If using paging, this may not be the total size of the dataset. If the data object
479 * used by the Reader contains the dataset size, then the getTotalCount() function returns
480 * the data set size</em>
482 getCount : function(){
483 return this.data.length || 0;
487 * Gets the total number of records in the dataset as returned by the server.
489 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
490 * the dataset size</em>
492 getTotalCount : function(){
493 return this.totalLength || 0;
497 * Returns the sort state of the Store as an object with two properties:
499 field {String} The name of the field by which the Records are sorted
500 direction {String} The sort order, "ASC" or "DESC"
503 getSortState : function(){
504 return this.sortInfo;
508 applySort : function(){
509 if(this.sortInfo && !this.remoteSort){
510 var s = this.sortInfo, f = s.field;
511 var st = this.fields.get(f).sortType;
512 var fn = function(r1, r2){
513 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
514 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
516 this.data.sort(s.direction, fn);
517 if(this.snapshot && this.snapshot != this.data){
518 this.snapshot.sort(s.direction, fn);
524 * Sets the default sort column and order to be used by the next load operation.
525 * @param {String} fieldName The name of the field to sort by.
526 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
528 setDefaultSort : function(field, dir){
529 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
534 * If remote sorting is used, the sort is performed on the server, and the cache is
535 * reloaded. If local sorting is used, the cache is sorted internally.
536 * @param {String} fieldName The name of the field to sort by.
537 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
539 sort : function(fieldName, dir){
540 var f = this.fields.get(fieldName);
542 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
544 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
545 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
550 this.sortToggle[f.name] = dir;
551 this.sortInfo = {field: f.name, direction: dir};
552 if(!this.remoteSort){
554 this.fireEvent("datachanged", this);
556 this.load(this.lastOptions);
561 * Calls the specified function for each of the Records in the cache.
562 * @param {Function} fn The function to call. The Record is passed as the first parameter.
563 * Returning <em>false</em> aborts and exits the iteration.
564 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
566 each : function(fn, scope){
567 this.data.each(fn, scope);
571 * Gets all records modified since the last commit. Modified records are persisted across load operations
572 * (e.g., during paging).
573 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
575 getModifiedRecords : function(){
576 return this.modified;
580 createFilterFn : function(property, value, anyMatch){
581 if(!value.exec){ // not a regex
582 value = String(value);
583 if(value.length == 0){
586 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
589 return value.test(r.data[property]);
594 * Sums the value of <i>property</i> for each record between start and end and returns the result.
595 * @param {String} property A field on your records
596 * @param {Number} start The record index to start at (defaults to 0)
597 * @param {Number} end The last record index to include (defaults to length - 1)
598 * @return {Number} The sum
600 sum : function(property, start, end){
601 var rs = this.data.items, v = 0;
603 end = (end || end === 0) ? end : rs.length-1;
605 for(var i = start; i <= end; i++){
606 v += (rs[i].data[property] || 0);
612 * Filter the records by a specified property.
613 * @param {String} field A field on your records
614 * @param {String/RegExp} value Either a string that the field
615 * should start with or a RegExp to test against the field
616 * @param {Boolean} anyMatch True to match any part not just the beginning
618 filter : function(property, value, anyMatch){
619 var fn = this.createFilterFn(property, value, anyMatch);
620 return fn ? this.filterBy(fn) : this.clearFilter();
624 * Filter by a function. The specified function will be called with each
625 * record in this data source. If the function returns true the record is included,
626 * otherwise it is filtered.
627 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
628 * @param {Object} scope (optional) The scope of the function (defaults to this)
630 filterBy : function(fn, scope){
631 this.snapshot = this.snapshot || this.data;
632 this.data = this.queryBy(fn, scope||this);
633 this.fireEvent("datachanged", this);
637 * Query the records by a specified property.
638 * @param {String} field A field on your records
639 * @param {String/RegExp} value Either a string that the field
640 * should start with or a RegExp to test against the field
641 * @param {Boolean} anyMatch True to match any part not just the beginning
642 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
644 query : function(property, value, anyMatch){
645 var fn = this.createFilterFn(property, value, anyMatch);
646 return fn ? this.queryBy(fn) : this.data.clone();
650 * Query by a function. The specified function will be called with each
651 * record in this data source. If the function returns true the record is included
653 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
654 * @param {Object} scope (optional) The scope of the function (defaults to this)
655 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
657 queryBy : function(fn, scope){
658 var data = this.snapshot || this.data;
659 return data.filterBy(fn, scope||this);
663 * Collects unique values for a particular dataIndex from this store.
664 * @param {String} dataIndex The property to collect
665 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
666 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
667 * @return {Array} An array of the unique values
669 collect : function(dataIndex, allowNull, bypassFilter){
670 var d = (bypassFilter === true && this.snapshot) ?
671 this.snapshot.items : this.data.items;
672 var v, sv, r = [], l = {};
673 for(var i = 0, len = d.length; i < len; i++){
674 v = d[i].data[dataIndex];
676 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
685 * Revert to a view of the Record cache with no filtering applied.
686 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
688 clearFilter : function(suppressEvent){
689 if(this.snapshot && this.snapshot != this.data){
690 this.data = this.snapshot;
691 delete this.snapshot;
692 if(suppressEvent !== true){
693 this.fireEvent("datachanged", this);
699 afterEdit : function(record){
700 if(this.modified.indexOf(record) == -1){
701 this.modified.push(record);
703 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
707 afterReject : function(record){
708 this.modified.remove(record);
709 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
713 afterCommit : function(record){
714 this.modified.remove(record);
715 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
719 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
720 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
722 commitChanges : function(){
723 var m = this.modified.slice(0);
725 for(var i = 0, len = m.length; i < len; i++){
731 * Cancel outstanding changes on all changed records.
733 rejectChanges : function(){
734 var m = this.modified.slice(0);
736 for(var i = 0, len = m.length; i < len; i++){
741 onMetaChange : function(meta, rtype, o){
742 this.recordType = rtype;
743 this.fields = rtype.prototype.fields;
744 delete this.snapshot;
745 this.sortInfo = meta.sortInfo || this.sortInfo;
747 this.fireEvent('metachange', this, this.reader.meta);
750 moveIndex : function(data, type)
752 var index = this.indexOf(data);
754 var newIndex = index + type;
758 this.insert(newIndex, data);