source: trunk/web/addons/job_monarch/lib/extjs/source/util/MixedCollection.js @ 619

Last change on this file since 619 was 619, checked in by ramonb, 15 years ago

lib/:

  • added new AJAX dependancies: ExtJS, pChart, Lightbox2
File size: 20.5 KB
Line 
1/*
2 * Ext JS Library 2.2.1
3 * Copyright(c) 2006-2009, Ext JS, LLC.
4 * licensing@extjs.com
5 *
6 * http://extjs.com/license
7 */
8
9/**
10 * @class Ext.util.MixedCollection
11 * @extends Ext.util.Observable
12 * A Collection class that maintains both numeric indexes and keys and exposes events.
13 * @constructor
14 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
15 * collection (defaults to false)
16 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
17 * and return the key value for that item.  This is used when available to look up the key on items that
18 * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
19 * equivalent to providing an implementation for the {@link #getKey} method.
20 */
21Ext.util.MixedCollection = function(allowFunctions, keyFn){
22    this.items = [];
23    this.map = {};
24    this.keys = [];
25    this.length = 0;
26    this.addEvents(
27        /**
28         * @event clear
29         * Fires when the collection is cleared.
30         */
31        "clear",
32        /**
33         * @event add
34         * Fires when an item is added to the collection.
35         * @param {Number} index The index at which the item was added.
36         * @param {Object} o The item added.
37         * @param {String} key The key associated with the added item.
38         */
39        "add",
40        /**
41         * @event replace
42         * Fires when an item is replaced in the collection.
43         * @param {String} key he key associated with the new added.
44         * @param {Object} old The item being replaced.
45         * @param {Object} new The new item.
46         */
47        "replace",
48        /**
49         * @event remove
50         * Fires when an item is removed from the collection.
51         * @param {Object} o The item being removed.
52         * @param {String} key (optional) The key associated with the removed item.
53         */
54        "remove",
55        "sort"
56    );
57    this.allowFunctions = allowFunctions === true;
58    if(keyFn){
59        this.getKey = keyFn;
60    }
61    Ext.util.MixedCollection.superclass.constructor.call(this);
62};
63
64Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, {
65    allowFunctions : false,
66
67/**
68 * Adds an item to the collection. Fires the {@link #add} event when complete.
69 * @param {String} key <p>The key to associate with the item, or the new item.</p>
70 * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key
71 * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection
72 * will be able to <i>derive</i> the key for the new item. In this case just pass the new item in
73 * this parameter.</p>
74 * @param {Object} o The item to add.
75 * @return {Object} The item added.
76 */
77    add : function(key, o){
78        if(arguments.length == 1){
79            o = arguments[0];
80            key = this.getKey(o);
81        }
82        if(typeof key == "undefined" || key === null){
83            this.length++;
84            this.items.push(o);
85            this.keys.push(null);
86        }else{
87            var old = this.map[key];
88            if(old){
89                return this.replace(key, o);
90            }
91            this.length++;
92            this.items.push(o);
93            this.map[key] = o;
94            this.keys.push(key);
95        }
96        this.fireEvent("add", this.length-1, o, key);
97        return o;
98    },
99
100/**
101  * MixedCollection has a generic way to fetch keys if you implement getKey.  The default implementation
102  * simply returns <tt style="font-weight:bold;">item.id</tt> but you can provide your own implementation
103  * to return a different value as in the following examples:
104<pre><code>
105// normal way
106var mc = new Ext.util.MixedCollection();
107mc.add(someEl.dom.id, someEl);
108mc.add(otherEl.dom.id, otherEl);
109//and so on
110
111// using getKey
112var mc = new Ext.util.MixedCollection();
113mc.getKey = function(el){
114   return el.dom.id;
115};
116mc.add(someEl);
117mc.add(otherEl);
118
119// or via the constructor
120var mc = new Ext.util.MixedCollection(false, function(el){
121   return el.dom.id;
122});
123mc.add(someEl);
124mc.add(otherEl);
125</code></pre>
126 * @param {Object} item The item for which to find the key.
127 * @return {Object} The key for the passed item.
128 */
129    getKey : function(o){
130         return o.id;
131    },
132
133/**
134 * Replaces an item in the collection. Fires the {@link #replace} event when complete.
135 * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p>
136 * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key
137 * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection
138 * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item
139 * with one having the same key value, then just pass the replacement item in this parameter.</p>
140 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate
141 * with that key.
142 * @return {Object}  The new item.
143 */
144    replace : function(key, o){
145        if(arguments.length == 1){
146            o = arguments[0];
147            key = this.getKey(o);
148        }
149        var old = this.item(key);
150        if(typeof key == "undefined" || key === null || typeof old == "undefined"){
151             return this.add(key, o);
152        }
153        var index = this.indexOfKey(key);
154        this.items[index] = o;
155        this.map[key] = o;
156        this.fireEvent("replace", key, old, o);
157        return o;
158    },
159
160/**
161 * Adds all elements of an Array or an Object to the collection.
162 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
163 * an Array of values, each of which are added to the collection.
164 */
165    addAll : function(objs){
166        if(arguments.length > 1 || Ext.isArray(objs)){
167            var args = arguments.length > 1 ? arguments : objs;
168            for(var i = 0, len = args.length; i < len; i++){
169                this.add(args[i]);
170            }
171        }else{
172            for(var key in objs){
173                if(this.allowFunctions || typeof objs[key] != "function"){
174                    this.add(key, objs[key]);
175                }
176            }
177        }
178    },
179
180/**
181 * Executes the specified function once for every item in the collection, passing the following arguments:
182 * <div class="mdetail-params"><ul>
183 * <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li>
184 * <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li>
185 * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>
186 * </ul></div>
187 * The function should return a boolean value. Returning false from the function will stop the iteration.
188 * @param {Function} fn The function to execute for each item.
189 * @param {Object} scope (optional) The scope in which to execute the function.
190 */
191    each : function(fn, scope){
192        var items = [].concat(this.items); // each safe for removal
193        for(var i = 0, len = items.length; i < len; i++){
194            if(fn.call(scope || items[i], items[i], i, len) === false){
195                break;
196            }
197        }
198    },
199
200/**
201 * Executes the specified function once for every key in the collection, passing each
202 * key, and its associated item as the first two parameters.
203 * @param {Function} fn The function to execute for each item.
204 * @param {Object} scope (optional) The scope in which to execute the function.
205 */
206    eachKey : function(fn, scope){
207        for(var i = 0, len = this.keys.length; i < len; i++){
208            fn.call(scope || window, this.keys[i], this.items[i], i, len);
209        }
210    },
211
212    /**
213     * Returns the first item in the collection which elicits a true return value from the
214     * passed selection function.
215     * @param {Function} fn The selection function to execute for each item.
216     * @param {Object} scope (optional) The scope in which to execute the function.
217     * @return {Object} The first item in the collection which returned true from the selection function.
218     */
219    find : function(fn, scope){
220        for(var i = 0, len = this.items.length; i < len; i++){
221            if(fn.call(scope || window, this.items[i], this.keys[i])){
222                return this.items[i];
223            }
224        }
225        return null;
226    },
227
228/**
229 * Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete.
230 * @param {Number} index The index to insert the item at.
231 * @param {String} key The key to associate with the new item, or the item itself.
232 * @param {Object} o (optional) If the second parameter was a key, the new item.
233 * @return {Object} The item inserted.
234 */
235    insert : function(index, key, o){
236        if(arguments.length == 2){
237            o = arguments[1];
238            key = this.getKey(o);
239        }
240        if(index >= this.length){
241            return this.add(key, o);
242        }
243        this.length++;
244        this.items.splice(index, 0, o);
245        if(typeof key != "undefined" && key != null){
246            this.map[key] = o;
247        }
248        this.keys.splice(index, 0, key);
249        this.fireEvent("add", index, o, key);
250        return o;
251    },
252
253/**
254 * Remove an item from the collection.
255 * @param {Object} o The item to remove.
256 * @return {Object} The item removed or false if no item was removed.
257 */
258    remove : function(o){
259        return this.removeAt(this.indexOf(o));
260    },
261
262/**
263 * Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete.
264 * @param {Number} index The index within the collection of the item to remove.
265 * @return {Object} The item removed or false if no item was removed.
266 */
267    removeAt : function(index){
268        if(index < this.length && index >= 0){
269            this.length--;
270            var o = this.items[index];
271            this.items.splice(index, 1);
272            var key = this.keys[index];
273            if(typeof key != "undefined"){
274                delete this.map[key];
275            }
276            this.keys.splice(index, 1);
277            this.fireEvent("remove", o, key);
278            return o;
279        }
280        return false;
281    },
282
283/**
284 * Removed an item associated with the passed key fom the collection.
285 * @param {String} key The key of the item to remove.
286 * @return {Object} The item removed or false if no item was removed.
287 */
288    removeKey : function(key){
289        return this.removeAt(this.indexOfKey(key));
290    },
291
292/**
293 * Returns the number of items in the collection.
294 * @return {Number} the number of items in the collection.
295 */
296    getCount : function(){
297        return this.length;
298    },
299
300/**
301 * Returns index within the collection of the passed Object.
302 * @param {Object} o The item to find the index of.
303 * @return {Number} index of the item. Returns -1 if not found.
304 */
305    indexOf : function(o){
306        return this.items.indexOf(o);
307    },
308
309/**
310 * Returns index within the collection of the passed key.
311 * @param {String} key The key to find the index of.
312 * @return {Number} index of the key.
313 */
314    indexOfKey : function(key){
315        return this.keys.indexOf(key);
316    },
317
318/**
319 * Returns the item associated with the passed key OR index. Key has priority over index.  This is the equivalent
320 * of calling {@link #key} first, then if nothing matched calling {@link #itemAt}.
321 * @param {String/Number} key The key or index of the item.
322 * @return {Object} The item associated with the passed key.
323 */
324    item : function(key){
325        var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
326        return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
327    },
328
329/**
330 * Returns the item at the specified index.
331 * @param {Number} index The index of the item.
332 * @return {Object} The item at the specified index.
333 */
334    itemAt : function(index){
335        return this.items[index];
336    },
337
338/**
339 * Returns the item associated with the passed key.
340 * @param {String/Number} key The key of the item.
341 * @return {Object} The item associated with the passed key.
342 */
343    key : function(key){
344        return this.map[key];
345    },
346
347/**
348 * Returns true if the collection contains the passed Object as an item.
349 * @param {Object} o  The Object to look for in the collection.
350 * @return {Boolean} True if the collection contains the Object as an item.
351 */
352    contains : function(o){
353        return this.indexOf(o) != -1;
354    },
355
356/**
357 * Returns true if the collection contains the passed Object as a key.
358 * @param {String} key The key to look for in the collection.
359 * @return {Boolean} True if the collection contains the Object as a key.
360 */
361    containsKey : function(key){
362        return typeof this.map[key] != "undefined";
363    },
364
365/**
366 * Removes all items from the collection.  Fires the {@link #clear} event when complete.
367 */
368    clear : function(){
369        this.length = 0;
370        this.items = [];
371        this.keys = [];
372        this.map = {};
373        this.fireEvent("clear");
374    },
375
376/**
377 * Returns the first item in the collection.
378 * @return {Object} the first item in the collection..
379 */
380    first : function(){
381        return this.items[0];
382    },
383
384/**
385 * Returns the last item in the collection.
386 * @return {Object} the last item in the collection..
387 */
388    last : function(){
389        return this.items[this.length-1];
390    },
391
392    // private
393    _sort : function(property, dir, fn){
394        var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
395        fn = fn || function(a, b){
396            return a-b;
397        };
398        var c = [], k = this.keys, items = this.items;
399        for(var i = 0, len = items.length; i < len; i++){
400            c[c.length] = {key: k[i], value: items[i], index: i};
401        }
402        c.sort(function(a, b){
403            var v = fn(a[property], b[property]) * dsc;
404            if(v == 0){
405                v = (a.index < b.index ? -1 : 1);
406            }
407            return v;
408        });
409        for(var i = 0, len = c.length; i < len; i++){
410            items[i] = c[i].value;
411            k[i] = c[i].key;
412        }
413        this.fireEvent("sort", this);
414    },
415
416    /**
417     * Sorts this collection with the passed comparison function
418     * @param {String} direction (optional) "ASC" or "DESC"
419     * @param {Function} fn (optional) comparison function
420     */
421    sort : function(dir, fn){
422        this._sort("value", dir, fn);
423    },
424
425    /**
426     * Sorts this collection by keys
427     * @param {String} direction (optional) "ASC" or "DESC"
428     * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
429     */
430    keySort : function(dir, fn){
431        this._sort("key", dir, fn || function(a, b){
432            var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
433            return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
434        });
435    },
436
437    /**
438     * Returns a range of items in this collection
439     * @param {Number} startIndex (optional) defaults to 0
440     * @param {Number} endIndex (optional) default to the last item
441     * @return {Array} An array of items
442     */
443    getRange : function(start, end){
444        var items = this.items;
445        if(items.length < 1){
446            return [];
447        }
448        start = start || 0;
449        end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
450        var r = [];
451        if(start <= end){
452            for(var i = start; i <= end; i++) {
453                    r[r.length] = items[i];
454            }
455        }else{
456            for(var i = start; i >= end; i--) {
457                    r[r.length] = items[i];
458            }
459        }
460        return r;
461    },
462
463    /**
464     * Filter the <i>objects</i> in this collection by a specific property.
465     * Returns a new collection that has been filtered.
466     * @param {String} property A property on your objects
467     * @param {String/RegExp} value Either string that the property values
468     * should start with or a RegExp to test against the property
469     * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
470     * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).
471     * @return {MixedCollection} The new filtered collection
472     */
473    filter : function(property, value, anyMatch, caseSensitive){
474        if(Ext.isEmpty(value, false)){
475            return this.clone();
476        }
477        value = this.createValueMatcher(value, anyMatch, caseSensitive);
478        return this.filterBy(function(o){
479            return o && value.test(o[property]);
480        });
481        },
482
483    /**
484     * Filter by a function. Returns a <i>new</i> collection that has been filtered.
485     * The passed function will be called with each object in the collection.
486     * If the function returns true, the value is included otherwise it is filtered.
487     * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
488     * @param {Object} scope (optional) The scope of the function (defaults to this)
489     * @return {MixedCollection} The new filtered collection
490     */
491    filterBy : function(fn, scope){
492        var r = new Ext.util.MixedCollection();
493        r.getKey = this.getKey;
494        var k = this.keys, it = this.items;
495        for(var i = 0, len = it.length; i < len; i++){
496            if(fn.call(scope||this, it[i], k[i])){
497                                r.add(k[i], it[i]);
498                        }
499        }
500        return r;
501    },
502
503    /**
504     * Finds the index of the first matching object in this collection by a specific property/value.
505     * @param {String} property The name of a property on your objects.
506     * @param {String/RegExp} value A string that the property values
507     * should start with or a RegExp to test against the property.
508     * @param {Number} start (optional) The index to start searching at (defaults to 0).
509     * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning.
510     * @param {Boolean} caseSensitive (optional) True for case sensitive comparison.
511     * @return {Number} The matched index or -1
512     */
513    findIndex : function(property, value, start, anyMatch, caseSensitive){
514        if(Ext.isEmpty(value, false)){
515            return -1;
516        }
517        value = this.createValueMatcher(value, anyMatch, caseSensitive);
518        return this.findIndexBy(function(o){
519            return o && value.test(o[property]);
520        }, null, start);
521        },
522
523    /**
524     * Find the index of the first matching object in this collection by a function.
525     * If the function returns <i>true</i> it is considered a match.
526     * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key).
527     * @param {Object} scope (optional) The scope of the function (defaults to this).
528     * @param {Number} start (optional) The index to start searching at (defaults to 0).
529     * @return {Number} The matched index or -1
530     */
531    findIndexBy : function(fn, scope, start){
532        var k = this.keys, it = this.items;
533        for(var i = (start||0), len = it.length; i < len; i++){
534            if(fn.call(scope||this, it[i], k[i])){
535                                return i;
536            }
537        }
538        if(typeof start == 'number' && start > 0){
539            for(var i = 0; i < start; i++){
540                if(fn.call(scope||this, it[i], k[i])){
541                    return i;
542                }
543            }
544        }
545        return -1;
546    },
547
548    // private
549    createValueMatcher : function(value, anyMatch, caseSensitive){
550        if(!value.exec){ // not a regex
551            value = String(value);
552            value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i');
553        }
554        return value;
555    },
556
557    /**
558     * Creates a shallow copy of this collection
559     * @return {MixedCollection}
560     */
561    clone : function(){
562        var r = new Ext.util.MixedCollection();
563        var k = this.keys, it = this.items;
564        for(var i = 0, len = it.length; i < len; i++){
565            r.add(k[i], it[i]);
566        }
567        r.getKey = this.getKey;
568        return r;
569    }
570});
571/**
572 * Returns the item associated with the passed key or index.
573 * @method
574 * @param {String/Number} key The key or index of the item.
575 * @return {Object} The item associated with the passed key.
576 */
577Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
Note: See TracBrowser for help on using the repository browser.