af4eb59a67f3433589df91c985032a31ff44e8fc
[roojs1] / Roo / data / Store.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13
14 /**
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>
19  * <p>
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>
22  * <p>
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.
25  * @constructor
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.
29  */
30 Roo.data.Store = function(config){
31     this.data = new Roo.util.MixedCollection(false);
32     this.data.getKey = function(o){
33         return o.id;
34     };
35     this.baseParams = {};
36     // private
37     this.paramNames = {
38         "start" : "start",
39         "limit" : "limit",
40         "sort" : "sort",
41         "dir" : "dir"
42     };
43
44     if(config && config.data){
45         this.inlineData = config.data;
46         delete config.data;
47     }
48
49     Roo.apply(this, config);
50     
51     if(this.reader){ // reader passed
52         this.reader = Roo.factory(this.reader, Roo.data);
53         this.reader.xmodule = this.xmodule || false;
54         if(!this.recordType){
55             this.recordType = this.reader.recordType;
56         }
57         if(this.reader.onMetaChange){
58             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
59         }
60     }
61
62     if(this.recordType){
63         this.fields = this.recordType.prototype.fields;
64     }
65     this.modified = [];
66
67     this.addEvents({
68         /**
69          * @event datachanged
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.
72          * @param {Store} this
73          */
74         datachanged : true,
75         /**
76          * @event metachange
77          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
78          * @param {Store} this
79          * @param {Object} meta The JSON metadata
80          */
81         metachange : true,
82         /**
83          * @event add
84          * Fires when Records have been added to the Store
85          * @param {Store} this
86          * @param {Roo.data.Record[]} records The array of Records added
87          * @param {Number} index The index at which the record(s) were added
88          */
89         add : true,
90         /**
91          * @event remove
92          * Fires when a Record has been removed from the Store
93          * @param {Store} this
94          * @param {Roo.data.Record} record The Record that was removed
95          * @param {Number} index The index at which the record was removed
96          */
97         remove : true,
98         /**
99          * @event update
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:
104          * <pre><code>
105  Roo.data.Record.EDIT
106  Roo.data.Record.REJECT
107  Roo.data.Record.COMMIT
108          * </code></pre>
109          */
110         update : true,
111         /**
112          * @event clear
113          * Fires when the data cache has been cleared.
114          * @param {Store} this
115          */
116         clear : true,
117         /**
118          * @event beforeload
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)
123          */
124         beforeload : true,
125         /**
126          * @event load
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)
131          */
132         load : true,
133         /**
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
138          * 
139          * @param {Proxy} 
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)
143          */
144         loadexception : true
145     });
146     
147     if(this.proxy){
148         this.proxy = Roo.factory(this.proxy, Roo.data);
149         this.proxy.xmodule = this.xmodule || false;
150         this.relayEvents(this.proxy,  ["loadexception"]);
151     }
152     this.sortToggle = {};
153
154     Roo.data.Store.superclass.constructor.call(this);
155
156     if(this.inlineData){
157         this.loadData(this.inlineData);
158         delete this.inlineData;
159     }
160 };
161 Roo.extend(Roo.data.Store, Roo.util.Observable, {
162      /**
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.
165     */
166     
167     /**
168     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
169     */
170     /**
171     * @cfg {Array} data Inline data to be loaded when the store is initialized.
172     */
173     /**
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.
176     */
177     /**
178     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
179     * on any HTTP request
180     */
181     /**
182     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
183     */
184     /**
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).
187     */
188     remoteSort : false,
189
190     /**
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).
193     */
194     pruneModifiedRecords : false,
195
196     // private
197     lastOptions : null,
198
199     /**
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.
202      */
203     add : function(records){
204         records = [].concat(records);
205         for(var i = 0, len = records.length; i < len; i++){
206             records[i].join(this);
207         }
208         var index = this.data.length;
209         this.data.addAll(records);
210         this.fireEvent("add", this, records, index);
211     },
212
213     /**
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.
216      */
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);
222         }
223         this.fireEvent("remove", this, record, index);
224     },
225
226     /**
227      * Remove all Records from the Store and fires the clear event.
228      */
229     removeAll : function(){
230         this.data.clear();
231         if(this.pruneModifiedRecords){
232             this.modified = [];
233         }
234         this.fireEvent("clear", this);
235     },
236
237     /**
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.
241      */
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);
247         }
248         this.fireEvent("add", this, records, index);
249     },
250
251     /**
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.
255      */
256     indexOf : function(record){
257         return this.data.indexOf(record);
258     },
259
260     /**
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.
264      */
265     indexOfId : function(id){
266         return this.data.indexOfKey(id);
267     },
268
269     /**
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.
273      */
274     getById : function(id){
275         return this.data.key(id);
276     },
277
278     /**
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.
282      */
283     getAt : function(index){
284         return this.data.itemAt(index);
285     },
286
287     /**
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
292      */
293     getRange : function(start, end){
294         return this.data.getRange(start, end);
295     },
296
297     // private
298     storeOptions : function(o){
299         o = Roo.apply({}, o);
300         delete o.callback;
301         delete o.scope;
302         this.lastOptions = o;
303     },
304
305     /**
306      * Loads the Record cache from the configured Proxy using the configured Reader.
307      * <p>
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.
311      * <p>
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>
315      * <p>
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>
325      * </ul>
326      */
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) {
334                 p._requestMeta = 1;
335             }
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;
340             }
341             this.proxy.load(p, this.reader, this.loadRecords, this, options);
342         }
343     },
344
345     /**
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).
351      */
352     reload : function(options){
353         this.load(Roo.applyIf(options||{}, this.lastOptions));
354     },
355
356     // private
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);
362             }
363             if(options.callback){
364                 options.callback.call(options.scope || this, [], options, false);
365             }
366             return;
367         }
368         // if data returned failure - throw an exception.
369         if (o.success === false) {
370             this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
371             return;
372         }
373         var r = o.records, t = o.totalRecords || r.length;
374         if(!options || options.add !== true){
375             if(this.pruneModifiedRecords){
376                 this.modified = [];
377             }
378             for(var i = 0, len = r.length; i < len; i++){
379                 r[i].join(this);
380             }
381             if(this.snapshot){
382                 this.data = this.snapshot;
383                 delete this.snapshot;
384             }
385             this.data.clear();
386             this.data.addAll(r);
387             this.totalLength = t;
388             this.applySort();
389             this.fireEvent("datachanged", this);
390         }else{
391             this.totalLength = Math.max(t, this.data.length+r.length);
392             this.add(r);
393         }
394         this.fireEvent("load", this, r, options);
395         if(options.callback){
396             options.callback.call(options.scope || this, r, options, true);
397         }
398     },
399
400     /**
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.
406      */
407     loadData : function(o, append){
408         var r = this.reader.readRecords(o);
409         this.loadRecords(r, {add: append}, true);
410     },
411
412     /**
413      * Gets the number of cached records.
414      * <p>
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>
418      */
419     getCount : function(){
420         return this.data.length || 0;
421     },
422
423     /**
424      * Gets the total number of records in the dataset as returned by the server.
425      * <p>
426      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
427      * the dataset size</em>
428      */
429     getTotalCount : function(){
430         return this.totalLength || 0;
431     },
432
433     /**
434      * Returns the sort state of the Store as an object with two properties:
435      * <pre><code>
436  field {String} The name of the field by which the Records are sorted
437  direction {String} The sort order, "ASC" or "DESC"
438      * </code></pre>
439      */
440     getSortState : function(){
441         return this.sortInfo;
442     },
443
444     // private
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);
452             };
453             this.data.sort(s.direction, fn);
454             if(this.snapshot && this.snapshot != this.data){
455                 this.snapshot.sort(s.direction, fn);
456             }
457         }
458     },
459
460     /**
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")
464      */
465     setDefaultSort : function(field, dir){
466         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
467     },
468
469     /**
470      * Sort the Records.
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")
475      */
476     sort : function(fieldName, dir){
477         var f = this.fields.get(fieldName);
478         if(!dir){
479             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
480                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
481             }else{
482                 dir = f.sortDir;
483             }
484         }
485         this.sortToggle[f.name] = dir;
486         this.sortInfo = {field: f.name, direction: dir};
487         if(!this.remoteSort){
488             this.applySort();
489             this.fireEvent("datachanged", this);
490         }else{
491             this.load(this.lastOptions);
492         }
493     },
494
495     /**
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).
500      */
501     each : function(fn, scope){
502         this.data.each(fn, scope);
503     },
504
505     /**
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.
509      */
510     getModifiedRecords : function(){
511         return this.modified;
512     },
513
514     // private
515     createFilterFn : function(property, value, anyMatch){
516         if(!value.exec){ // not a regex
517             value = String(value);
518             if(value.length == 0){
519                 return false;
520             }
521             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
522         }
523         return function(r){
524             return value.test(r.data[property]);
525         };
526     },
527
528     /**
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
534      */
535     sum : function(property, start, end){
536         var rs = this.data.items, v = 0;
537         start = start || 0;
538         end = (end || end === 0) ? end : rs.length-1;
539
540         for(var i = start; i <= end; i++){
541             v += (rs[i].data[property] || 0);
542         }
543         return v;
544     },
545
546     /**
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
552      */
553     filter : function(property, value, anyMatch){
554         var fn = this.createFilterFn(property, value, anyMatch);
555         return fn ? this.filterBy(fn) : this.clearFilter();
556     },
557
558     /**
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)
564      */
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);
569     },
570
571     /**
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
578      */
579     query : function(property, value, anyMatch){
580         var fn = this.createFilterFn(property, value, anyMatch);
581         return fn ? this.queryBy(fn) : this.data.clone();
582     },
583
584     /**
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
587      * in the results.
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
591      **/
592     queryBy : function(fn, scope){
593         var data = this.snapshot || this.data;
594         return data.filterBy(fn, scope||this);
595     },
596
597     /**
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
603      **/
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];
610             sv = String(v);
611             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
612                 l[sv] = true;
613                 r[r.length] = v;
614             }
615         }
616         return r;
617     },
618
619     /**
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
622      */
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);
629             }
630         }
631     },
632
633     // private
634     afterEdit : function(record){
635         if(this.modified.indexOf(record) == -1){
636             this.modified.push(record);
637         }
638         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
639     },
640
641     // private
642     afterReject : function(record){
643         this.modified.remove(record);
644         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
645     },
646
647     // private
648     afterCommit : function(record){
649         this.modified.remove(record);
650         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
651     },
652
653     /**
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.
656      */
657     commitChanges : function(){
658         var m = this.modified.slice(0);
659         this.modified = [];
660         for(var i = 0, len = m.length; i < len; i++){
661             m[i].commit();
662         }
663     },
664
665     /**
666      * Cancel outstanding changes on all changed records.
667      */
668     rejectChanges : function(){
669         var m = this.modified.slice(0);
670         this.modified = [];
671         for(var i = 0, len = m.length; i < len; i++){
672             m[i].reject();
673         }
674     },
675
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;
681         this.modified = [];
682         this.fireEvent('metachange', this, this.reader.meta);
683     }
684 });