initial import
[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         if(!this.recordType){
54             this.recordType = this.reader.recordType;
55         }
56         if(this.reader.onMetaChange){
57             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
58         }
59     }
60
61     if(this.recordType){
62         this.fields = this.recordType.prototype.fields;
63     }
64     this.modified = [];
65
66     this.addEvents({
67         /**
68          * @event datachanged
69          * Fires when the data cache has changed, and a widget which is using this Store
70          * as a Record cache should refresh its view.
71          * @param {Store} this
72          */
73         datachanged : true,
74         /**
75          * @event metachange
76          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
77          * @param {Store} this
78          * @param {Object} meta The JSON metadata
79          */
80         metachange : true,
81         /**
82          * @event add
83          * Fires when Records have been added to the Store
84          * @param {Store} this
85          * @param {Roo.data.Record[]} records The array of Records added
86          * @param {Number} index The index at which the record(s) were added
87          */
88         add : true,
89         /**
90          * @event remove
91          * Fires when a Record has been removed from the Store
92          * @param {Store} this
93          * @param {Roo.data.Record} record The Record that was removed
94          * @param {Number} index The index at which the record was removed
95          */
96         remove : true,
97         /**
98          * @event update
99          * Fires when a Record has been updated
100          * @param {Store} this
101          * @param {Roo.data.Record} record The Record that was updated
102          * @param {String} operation The update operation being performed.  Value may be one of:
103          * <pre><code>
104  Roo.data.Record.EDIT
105  Roo.data.Record.REJECT
106  Roo.data.Record.COMMIT
107          * </code></pre>
108          */
109         update : true,
110         /**
111          * @event clear
112          * Fires when the data cache has been cleared.
113          * @param {Store} this
114          */
115         clear : true,
116         /**
117          * @event beforeload
118          * Fires before a request is made for a new data object.  If the beforeload handler returns false
119          * the load action will be canceled.
120          * @param {Store} this
121          * @param {Object} options The loading options that were specified (see {@link #load} for details)
122          */
123         beforeload : true,
124         /**
125          * @event load
126          * Fires after a new set of Records has been loaded.
127          * @param {Store} this
128          * @param {Roo.data.Record[]} records The Records that were loaded
129          * @param {Object} options The loading options that were specified (see {@link #load} for details)
130          */
131         load : true,
132         /**
133          * @event loadexception
134          * Fires if an exception occurs in the Proxy during loading.
135          * Called with the signature of the Proxy's "loadexception" event.
136          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
137          * 
138          * @param {Proxy} 
139          * @param {Object} return from JsonData.reader() - success, totalRecords, records
140          * @param {Object} load options 
141          * @param {Object} jsonData from your request (normally this contains the Exception)
142          */
143         loadexception : true
144     });
145     
146     if(this.proxy){
147         this.proxy = Roo.factory(this.proxy, Roo.data);
148         this.relayEvents(this.proxy,  ["loadexception"]);
149     }
150     this.sortToggle = {};
151
152     Roo.data.Store.superclass.constructor.call(this);
153
154     if(this.inlineData){
155         this.loadData(this.inlineData);
156         delete this.inlineData;
157     }
158 };
159 Roo.extend(Roo.data.Store, Roo.util.Observable, {
160      /**
161     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
162     * without a remote query - used by combo/forms at present.
163     */
164     
165     /**
166     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
167     */
168     /**
169     * @cfg {Array} data Inline data to be loaded when the store is initialized.
170     */
171     /**
172     * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
173     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
174     */
175     /**
176     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
177     * on any HTTP request
178     */
179     /**
180     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
181     */
182     /**
183     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
184     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
185     */
186     remoteSort : false,
187
188     /**
189     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
190      * loaded or when a record is removed. (defaults to false).
191     */
192     pruneModifiedRecords : false,
193
194     // private
195     lastOptions : null,
196
197     /**
198      * Add Records to the Store and fires the add event.
199      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
200      */
201     add : function(records){
202         records = [].concat(records);
203         for(var i = 0, len = records.length; i < len; i++){
204             records[i].join(this);
205         }
206         var index = this.data.length;
207         this.data.addAll(records);
208         this.fireEvent("add", this, records, index);
209     },
210
211     /**
212      * Remove a Record from the Store and fires the remove event.
213      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
214      */
215     remove : function(record){
216         var index = this.data.indexOf(record);
217         this.data.removeAt(index);
218         if(this.pruneModifiedRecords){
219             this.modified.remove(record);
220         }
221         this.fireEvent("remove", this, record, index);
222     },
223
224     /**
225      * Remove all Records from the Store and fires the clear event.
226      */
227     removeAll : function(){
228         this.data.clear();
229         if(this.pruneModifiedRecords){
230             this.modified = [];
231         }
232         this.fireEvent("clear", this);
233     },
234
235     /**
236      * Inserts Records to the Store at the given index and fires the add event.
237      * @param {Number} index The start index at which to insert the passed Records.
238      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
239      */
240     insert : function(index, records){
241         records = [].concat(records);
242         for(var i = 0, len = records.length; i < len; i++){
243             this.data.insert(index, records[i]);
244             records[i].join(this);
245         }
246         this.fireEvent("add", this, records, index);
247     },
248
249     /**
250      * Get the index within the cache of the passed Record.
251      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
252      * @return {Number} The index of the passed Record. Returns -1 if not found.
253      */
254     indexOf : function(record){
255         return this.data.indexOf(record);
256     },
257
258     /**
259      * Get the index within the cache of the Record with the passed id.
260      * @param {String} id The id of the Record to find.
261      * @return {Number} The index of the Record. Returns -1 if not found.
262      */
263     indexOfId : function(id){
264         return this.data.indexOfKey(id);
265     },
266
267     /**
268      * Get the Record with the specified id.
269      * @param {String} id The id of the Record to find.
270      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
271      */
272     getById : function(id){
273         return this.data.key(id);
274     },
275
276     /**
277      * Get the Record at the specified index.
278      * @param {Number} index The index of the Record to find.
279      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
280      */
281     getAt : function(index){
282         return this.data.itemAt(index);
283     },
284
285     /**
286      * Returns a range of Records between specified indices.
287      * @param {Number} startIndex (optional) The starting index (defaults to 0)
288      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
289      * @return {Roo.data.Record[]} An array of Records
290      */
291     getRange : function(start, end){
292         return this.data.getRange(start, end);
293     },
294
295     // private
296     storeOptions : function(o){
297         o = Roo.apply({}, o);
298         delete o.callback;
299         delete o.scope;
300         this.lastOptions = o;
301     },
302
303     /**
304      * Loads the Record cache from the configured Proxy using the configured Reader.
305      * <p>
306      * If using remote paging, then the first load call must specify the <em>start</em>
307      * and <em>limit</em> properties in the options.params property to establish the initial
308      * position within the dataset, and the number of Records to cache on each read from the Proxy.
309      * <p>
310      * <strong>It is important to note that for remote data sources, loading is asynchronous,
311      * and this call will return before the new data has been loaded. Perform any post-processing
312      * in a callback function, or in a "load" event handler.</strong>
313      * <p>
314      * @param {Object} options An object containing properties which control loading options:<ul>
315      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
316      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
317      * passed the following arguments:<ul>
318      * <li>r : Roo.data.Record[]</li>
319      * <li>options: Options object from the load call</li>
320      * <li>success: Boolean success indicator</li></ul></li>
321      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
322      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
323      * </ul>
324      */
325     load : function(options){
326         options = options || {};
327         if(this.fireEvent("beforeload", this, options) !== false){
328             this.storeOptions(options);
329             var p = Roo.apply(options.params || {}, this.baseParams);
330             if(this.sortInfo && this.remoteSort){
331                 var pn = this.paramNames;
332                 p[pn["sort"]] = this.sortInfo.field;
333                 p[pn["dir"]] = this.sortInfo.direction;
334             }
335             this.proxy.load(p, this.reader, this.loadRecords, this, options);
336         }
337     },
338
339     /**
340      * Reloads the Record cache from the configured Proxy using the configured Reader and
341      * the options from the last load operation performed.
342      * @param {Object} options (optional) An object containing properties which may override the options
343      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
344      * the most recently used options are reused).
345      */
346     reload : function(options){
347         this.load(Roo.applyIf(options||{}, this.lastOptions));
348     },
349
350     // private
351     // Called as a callback by the Reader during a load operation.
352     loadRecords : function(o, options, success){
353         if(!o || success === false){
354             if(success !== false){
355                 this.fireEvent("load", this, [], options);
356             }
357             if(options.callback){
358                 options.callback.call(options.scope || this, [], options, false);
359             }
360             return;
361         }
362         // if data returned failure - throw an exception.
363         if (o.success === false) {
364             this.fireEvent("loadexception", this, o, options, this.reader.jsonData);
365             return;
366         }
367         var r = o.records, t = o.totalRecords || r.length;
368         if(!options || options.add !== true){
369             if(this.pruneModifiedRecords){
370                 this.modified = [];
371             }
372             for(var i = 0, len = r.length; i < len; i++){
373                 r[i].join(this);
374             }
375             if(this.snapshot){
376                 this.data = this.snapshot;
377                 delete this.snapshot;
378             }
379             this.data.clear();
380             this.data.addAll(r);
381             this.totalLength = t;
382             this.applySort();
383             this.fireEvent("datachanged", this);
384         }else{
385             this.totalLength = Math.max(t, this.data.length+r.length);
386             this.add(r);
387         }
388         this.fireEvent("load", this, r, options);
389         if(options.callback){
390             options.callback.call(options.scope || this, r, options, true);
391         }
392     },
393
394     /**
395      * Loads data from a passed data block. A Reader which understands the format of the data
396      * must have been configured in the constructor.
397      * @param {Object} data The data block from which to read the Records.  The format of the data expected
398      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
399      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
400      */
401     loadData : function(o, append){
402         var r = this.reader.readRecords(o);
403         this.loadRecords(r, {add: append}, true);
404     },
405
406     /**
407      * Gets the number of cached records.
408      * <p>
409      * <em>If using paging, this may not be the total size of the dataset. If the data object
410      * used by the Reader contains the dataset size, then the getTotalCount() function returns
411      * the data set size</em>
412      */
413     getCount : function(){
414         return this.data.length || 0;
415     },
416
417     /**
418      * Gets the total number of records in the dataset as returned by the server.
419      * <p>
420      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
421      * the dataset size</em>
422      */
423     getTotalCount : function(){
424         return this.totalLength || 0;
425     },
426
427     /**
428      * Returns the sort state of the Store as an object with two properties:
429      * <pre><code>
430  field {String} The name of the field by which the Records are sorted
431  direction {String} The sort order, "ASC" or "DESC"
432      * </code></pre>
433      */
434     getSortState : function(){
435         return this.sortInfo;
436     },
437
438     // private
439     applySort : function(){
440         if(this.sortInfo && !this.remoteSort){
441             var s = this.sortInfo, f = s.field;
442             var st = this.fields.get(f).sortType;
443             var fn = function(r1, r2){
444                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
445                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
446             };
447             this.data.sort(s.direction, fn);
448             if(this.snapshot && this.snapshot != this.data){
449                 this.snapshot.sort(s.direction, fn);
450             }
451         }
452     },
453
454     /**
455      * Sets the default sort column and order to be used by the next load operation.
456      * @param {String} fieldName The name of the field to sort by.
457      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
458      */
459     setDefaultSort : function(field, dir){
460         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
461     },
462
463     /**
464      * Sort the Records.
465      * If remote sorting is used, the sort is performed on the server, and the cache is
466      * reloaded. If local sorting is used, the cache is sorted internally.
467      * @param {String} fieldName The name of the field to sort by.
468      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
469      */
470     sort : function(fieldName, dir){
471         var f = this.fields.get(fieldName);
472         if(!dir){
473             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
474                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
475             }else{
476                 dir = f.sortDir;
477             }
478         }
479         this.sortToggle[f.name] = dir;
480         this.sortInfo = {field: f.name, direction: dir};
481         if(!this.remoteSort){
482             this.applySort();
483             this.fireEvent("datachanged", this);
484         }else{
485             this.load(this.lastOptions);
486         }
487     },
488
489     /**
490      * Calls the specified function for each of the Records in the cache.
491      * @param {Function} fn The function to call. The Record is passed as the first parameter.
492      * Returning <em>false</em> aborts and exits the iteration.
493      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
494      */
495     each : function(fn, scope){
496         this.data.each(fn, scope);
497     },
498
499     /**
500      * Gets all records modified since the last commit.  Modified records are persisted across load operations
501      * (e.g., during paging).
502      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
503      */
504     getModifiedRecords : function(){
505         return this.modified;
506     },
507
508     // private
509     createFilterFn : function(property, value, anyMatch){
510         if(!value.exec){ // not a regex
511             value = String(value);
512             if(value.length == 0){
513                 return false;
514             }
515             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
516         }
517         return function(r){
518             return value.test(r.data[property]);
519         };
520     },
521
522     /**
523      * Sums the value of <i>property</i> for each record between start and end and returns the result.
524      * @param {String} property A field on your records
525      * @param {Number} start The record index to start at (defaults to 0)
526      * @param {Number} end The last record index to include (defaults to length - 1)
527      * @return {Number} The sum
528      */
529     sum : function(property, start, end){
530         var rs = this.data.items, v = 0;
531         start = start || 0;
532         end = (end || end === 0) ? end : rs.length-1;
533
534         for(var i = start; i <= end; i++){
535             v += (rs[i].data[property] || 0);
536         }
537         return v;
538     },
539
540     /**
541      * Filter the records by a specified property.
542      * @param {String} field A field on your records
543      * @param {String/RegExp} value Either a string that the field
544      * should start with or a RegExp to test against the field
545      * @param {Boolean} anyMatch True to match any part not just the beginning
546      */
547     filter : function(property, value, anyMatch){
548         var fn = this.createFilterFn(property, value, anyMatch);
549         return fn ? this.filterBy(fn) : this.clearFilter();
550     },
551
552     /**
553      * Filter by a function. The specified function will be called with each
554      * record in this data source. If the function returns true the record is included,
555      * otherwise it is filtered.
556      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
557      * @param {Object} scope (optional) The scope of the function (defaults to this)
558      */
559     filterBy : function(fn, scope){
560         this.snapshot = this.snapshot || this.data;
561         this.data = this.queryBy(fn, scope||this);
562         this.fireEvent("datachanged", this);
563     },
564
565     /**
566      * Query the records by a specified property.
567      * @param {String} field A field on your records
568      * @param {String/RegExp} value Either a string that the field
569      * should start with or a RegExp to test against the field
570      * @param {Boolean} anyMatch True to match any part not just the beginning
571      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
572      */
573     query : function(property, value, anyMatch){
574         var fn = this.createFilterFn(property, value, anyMatch);
575         return fn ? this.queryBy(fn) : this.data.clone();
576     },
577
578     /**
579      * Query by a function. The specified function will be called with each
580      * record in this data source. If the function returns true the record is included
581      * in the results.
582      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
583      * @param {Object} scope (optional) The scope of the function (defaults to this)
584       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
585      **/
586     queryBy : function(fn, scope){
587         var data = this.snapshot || this.data;
588         return data.filterBy(fn, scope||this);
589     },
590
591     /**
592      * Collects unique values for a particular dataIndex from this store.
593      * @param {String} dataIndex The property to collect
594      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
595      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
596      * @return {Array} An array of the unique values
597      **/
598     collect : function(dataIndex, allowNull, bypassFilter){
599         var d = (bypassFilter === true && this.snapshot) ?
600                 this.snapshot.items : this.data.items;
601         var v, sv, r = [], l = {};
602         for(var i = 0, len = d.length; i < len; i++){
603             v = d[i].data[dataIndex];
604             sv = String(v);
605             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
606                 l[sv] = true;
607                 r[r.length] = v;
608             }
609         }
610         return r;
611     },
612
613     /**
614      * Revert to a view of the Record cache with no filtering applied.
615      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
616      */
617     clearFilter : function(suppressEvent){
618         if(this.snapshot && this.snapshot != this.data){
619             this.data = this.snapshot;
620             delete this.snapshot;
621             if(suppressEvent !== true){
622                 this.fireEvent("datachanged", this);
623             }
624         }
625     },
626
627     // private
628     afterEdit : function(record){
629         if(this.modified.indexOf(record) == -1){
630             this.modified.push(record);
631         }
632         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
633     },
634
635     // private
636     afterReject : function(record){
637         this.modified.remove(record);
638         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
639     },
640
641     // private
642     afterCommit : function(record){
643         this.modified.remove(record);
644         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
645     },
646
647     /**
648      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
649      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
650      */
651     commitChanges : function(){
652         var m = this.modified.slice(0);
653         this.modified = [];
654         for(var i = 0, len = m.length; i < len; i++){
655             m[i].commit();
656         }
657     },
658
659     /**
660      * Cancel outstanding changes on all changed records.
661      */
662     rejectChanges : function(){
663         var m = this.modified.slice(0);
664         this.modified = [];
665         for(var i = 0, len = m.length; i < len; i++){
666             m[i].reject();
667         }
668     },
669
670     onMetaChange : function(meta, rtype, o){
671         this.recordType = rtype;
672         this.fields = rtype.prototype.fields;
673         delete this.snapshot;
674         this.sortInfo = meta.sortInfo;
675         this.modified = [];
676         this.fireEvent('metachange', this, this.reader.meta);
677     }
678 });