/javascripts/lib/src/util/MixedCollection.js

https://bitbucket.org/ksokmesa/sina-asian · JavaScript · 669 lines · 320 code · 48 blank · 301 comment · 78 complexity · 7165554a47313d532243bc1ba11bda07 MD5 · raw file

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