PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/ansible/roles/appnode/files/oozie_server/oozie/oozie-server/webapps/oozie/ext-2.2/source/core/Ext.js

https://gitlab.com/wardcomm/code_examples
JavaScript | 1031 lines | 428 code | 58 blank | 545 comment | 157 complexity | aeb7ce5c587e7b5321635f4f3c91969c MD5 | raw file
  1. /*
  2. * Ext JS Library 2.2
  3. * Copyright(c) 2006-2008, Ext JS, LLC.
  4. * licensing@extjs.com
  5. *
  6. * http://extjs.com/license
  7. */
  8. Ext = {version: '2.2'};
  9. // for old browsers
  10. window["undefined"] = window["undefined"];
  11. /**
  12. * @class Ext
  13. * Ext core utilities and functions.
  14. * @singleton
  15. */
  16. /**
  17. * Copies all the properties of config to obj.
  18. * @param {Object} obj The receiver of the properties
  19. * @param {Object} config The source of the properties
  20. * @param {Object} defaults A different object that will also be applied for default values
  21. * @return {Object} returns obj
  22. * @member Ext apply
  23. */
  24. Ext.apply = function(o, c, defaults){
  25. if(defaults){
  26. // no "this" reference for friendly out of scope calls
  27. Ext.apply(o, defaults);
  28. }
  29. if(o && c && typeof c == 'object'){
  30. for(var p in c){
  31. o[p] = c[p];
  32. }
  33. }
  34. return o;
  35. };
  36. (function(){
  37. var idSeed = 0;
  38. var ua = navigator.userAgent.toLowerCase();
  39. var isStrict = document.compatMode == "CSS1Compat",
  40. isOpera = ua.indexOf("opera") > -1,
  41. isSafari = (/webkit|khtml/).test(ua),
  42. isSafari3 = isSafari && ua.indexOf('webkit/5') != -1,
  43. isIE = !isOpera && ua.indexOf("msie") > -1,
  44. isIE7 = !isOpera && ua.indexOf("msie 7") > -1,
  45. isGecko = !isSafari && ua.indexOf("gecko") > -1,
  46. isGecko3 = !isSafari && ua.indexOf("rv:1.9") > -1,
  47. isBorderBox = isIE && !isStrict,
  48. isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
  49. isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
  50. isAir = (ua.indexOf("adobeair") != -1),
  51. isLinux = (ua.indexOf("linux") != -1),
  52. isSecure = window.location.href.toLowerCase().indexOf("https") === 0;
  53. // remove css image flicker
  54. if(isIE && !isIE7){
  55. try{
  56. document.execCommand("BackgroundImageCache", false, true);
  57. }catch(e){}
  58. }
  59. Ext.apply(Ext, {
  60. /**
  61. * True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode
  62. * @type Boolean
  63. */
  64. isStrict : isStrict,
  65. /**
  66. * True if the page is running over SSL
  67. * @type Boolean
  68. */
  69. isSecure : isSecure,
  70. /**
  71. * True when the document is fully initialized and ready for action
  72. * @type Boolean
  73. */
  74. isReady : false,
  75. /**
  76. * True to automatically uncache orphaned Ext.Elements periodically (defaults to true)
  77. * @type Boolean
  78. */
  79. enableGarbageCollector : true,
  80. /**
  81. * True to automatically purge event listeners after uncaching an element (defaults to false).
  82. * Note: this only happens if enableGarbageCollector is true.
  83. * @type Boolean
  84. */
  85. enableListenerCollection:false,
  86. /**
  87. * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
  88. * the IE insecure content warning (defaults to javascript:false).
  89. * @type String
  90. */
  91. SSL_SECURE_URL : "javascript:false",
  92. /**
  93. * URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images. (Defaults to
  94. * "http://extjs.com/s.gif" and you should change this to a URL on your server).
  95. * @type String
  96. */
  97. BLANK_IMAGE_URL : "http:/"+"/extjs.com/s.gif",
  98. /**
  99. * A reusable empty function
  100. * @property
  101. * @type Function
  102. */
  103. emptyFn : function(){},
  104. /**
  105. * Copies all the properties of config to obj if they don't already exist.
  106. * @param {Object} obj The receiver of the properties
  107. * @param {Object} config The source of the properties
  108. * @return {Object} returns obj
  109. */
  110. applyIf : function(o, c){
  111. if(o && c){
  112. for(var p in c){
  113. if(typeof o[p] == "undefined"){ o[p] = c[p]; }
  114. }
  115. }
  116. return o;
  117. },
  118. /**
  119. * Applies event listeners to elements by selectors when the document is ready.
  120. * The event name is specified with an @ suffix.
  121. <pre><code>
  122. Ext.addBehaviors({
  123. // add a listener for click on all anchors in element with id foo
  124. '#foo a@click' : function(e, t){
  125. // do something
  126. },
  127. // add the same listener to multiple selectors (separated by comma BEFORE the @)
  128. '#foo a, #bar span.some-class@mouseover' : function(){
  129. // do something
  130. }
  131. });
  132. </code></pre>
  133. * @param {Object} obj The list of behaviors to apply
  134. */
  135. addBehaviors : function(o){
  136. if(!Ext.isReady){
  137. Ext.onReady(function(){
  138. Ext.addBehaviors(o);
  139. });
  140. return;
  141. }
  142. var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
  143. for(var b in o){
  144. var parts = b.split('@');
  145. if(parts[1]){ // for Object prototype breakers
  146. var s = parts[0];
  147. if(!cache[s]){
  148. cache[s] = Ext.select(s);
  149. }
  150. cache[s].on(parts[1], o[b]);
  151. }
  152. }
  153. cache = null;
  154. },
  155. /**
  156. * Generates unique ids. If the element already has an id, it is unchanged
  157. * @param {Mixed} el (optional) The element to generate an id for
  158. * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
  159. * @return {String} The generated Id.
  160. */
  161. id : function(el, prefix){
  162. prefix = prefix || "ext-gen";
  163. el = Ext.getDom(el);
  164. var id = prefix + (++idSeed);
  165. return el ? (el.id ? el.id : (el.id = id)) : id;
  166. },
  167. /**
  168. * Extends one class with another class and optionally overrides members with the passed literal. This class
  169. * also adds the function "override()" to the class that can be used to override
  170. * members on an instance.
  171. * * <p>
  172. * This function also supports a 2-argument call in which the subclass's constructor is
  173. * not passed as an argument. In this form, the parameters are as follows:</p><p>
  174. * <div class="mdetail-params"><ul>
  175. * <li><code>superclass</code>
  176. * <div class="sub-desc">The class being extended</div></li>
  177. * <li><code>overrides</code>
  178. * <div class="sub-desc">A literal with members which are copied into the subclass's
  179. * prototype, and are therefore shared among all instances of the new class.<p>
  180. * This may contain a special member named <tt><b>constructor</b></tt>. This is used
  181. * to define the constructor of the new class, and is returned. If this property is
  182. * <i>not</i> specified, a constructor is generated and returned which just calls the
  183. * superclass's constructor passing on its parameters.</p></div></li>
  184. * </ul></div></p><p>
  185. * For example, to create a subclass of the Ext GridPanel:
  186. * <pre><code>
  187. MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
  188. constructor: function(config) {
  189. // Your preprocessing here
  190. MyGridPanel.superclass.constructor.apply(this, arguments);
  191. // Your postprocessing here
  192. },
  193. yourMethod: function() {
  194. // etc.
  195. }
  196. });
  197. </code></pre>
  198. * </p>
  199. * @param {Function} subclass The class inheriting the functionality
  200. * @param {Function} superclass The class being extended
  201. * @param {Object} overrides (optional) A literal with members which are copied into the subclass's
  202. * prototype, and are therefore shared between all instances of the new class.
  203. * @return {Function} The subclass constructor.
  204. * @method extend
  205. */
  206. extend : function(){
  207. // inline overrides
  208. var io = function(o){
  209. for(var m in o){
  210. this[m] = o[m];
  211. }
  212. };
  213. var oc = Object.prototype.constructor;
  214. return function(sb, sp, overrides){
  215. if(typeof sp == 'object'){
  216. overrides = sp;
  217. sp = sb;
  218. sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);};
  219. }
  220. var F = function(){}, sbp, spp = sp.prototype;
  221. F.prototype = spp;
  222. sbp = sb.prototype = new F();
  223. sbp.constructor=sb;
  224. sb.superclass=spp;
  225. if(spp.constructor == oc){
  226. spp.constructor=sp;
  227. }
  228. sb.override = function(o){
  229. Ext.override(sb, o);
  230. };
  231. sbp.override = io;
  232. Ext.override(sb, overrides);
  233. sb.extend = function(o){Ext.extend(sb, o);};
  234. return sb;
  235. };
  236. }(),
  237. /**
  238. * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
  239. * Usage:<pre><code>
  240. Ext.override(MyClass, {
  241. newMethod1: function(){
  242. // etc.
  243. },
  244. newMethod2: function(foo){
  245. // etc.
  246. }
  247. });
  248. </code></pre>
  249. * @param {Object} origclass The class to override
  250. * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
  251. * containing one or more methods.
  252. * @method override
  253. */
  254. override : function(origclass, overrides){
  255. if(overrides){
  256. var p = origclass.prototype;
  257. for(var method in overrides){
  258. p[method] = overrides[method];
  259. }
  260. }
  261. },
  262. /**
  263. * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
  264. * <pre><code>
  265. Ext.namespace('Company', 'Company.data');
  266. Company.Widget = function() { ... }
  267. Company.data.CustomStore = function(config) { ... }
  268. </code></pre>
  269. * @param {String} namespace1
  270. * @param {String} namespace2
  271. * @param {String} etc
  272. * @method namespace
  273. */
  274. namespace : function(){
  275. var a=arguments, o=null, i, j, d, rt;
  276. for (i=0; i<a.length; ++i) {
  277. d=a[i].split(".");
  278. rt = d[0];
  279. eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
  280. for (j=1; j<d.length; ++j) {
  281. o[d[j]]=o[d[j]] || {};
  282. o=o[d[j]];
  283. }
  284. }
  285. },
  286. /**
  287. * Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
  288. * @param {Object} o
  289. * @return {String}
  290. */
  291. urlEncode : function(o){
  292. if(!o){
  293. return "";
  294. }
  295. var buf = [];
  296. for(var key in o){
  297. var ov = o[key], k = encodeURIComponent(key);
  298. var type = typeof ov;
  299. if(type == 'undefined'){
  300. buf.push(k, "=&");
  301. }else if(type != "function" && type != "object"){
  302. buf.push(k, "=", encodeURIComponent(ov), "&");
  303. }else if(Ext.isArray(ov)){
  304. if (ov.length) {
  305. for(var i = 0, len = ov.length; i < len; i++) {
  306. buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
  307. }
  308. } else {
  309. buf.push(k, "=&");
  310. }
  311. }
  312. }
  313. buf.pop();
  314. return buf.join("");
  315. },
  316. /**
  317. * Takes an encoded URL and and converts it to an object. e.g. Ext.urlDecode("foo=1&bar=2"); would return {foo: 1, bar: 2} or Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", true); would return {foo: 1, bar: [2, 3, 4]}.
  318. * @param {String} string
  319. * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
  320. * @return {Object} A literal with members
  321. */
  322. urlDecode : function(string, overwrite){
  323. if(!string || !string.length){
  324. return {};
  325. }
  326. var obj = {};
  327. var pairs = string.split('&');
  328. var pair, name, value;
  329. for(var i = 0, len = pairs.length; i < len; i++){
  330. pair = pairs[i].split('=');
  331. name = decodeURIComponent(pair[0]);
  332. value = decodeURIComponent(pair[1]);
  333. if(overwrite !== true){
  334. if(typeof obj[name] == "undefined"){
  335. obj[name] = value;
  336. }else if(typeof obj[name] == "string"){
  337. obj[name] = [obj[name]];
  338. obj[name].push(value);
  339. }else{
  340. obj[name].push(value);
  341. }
  342. }else{
  343. obj[name] = value;
  344. }
  345. }
  346. return obj;
  347. },
  348. /**
  349. * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
  350. * passed array is not really an array, your function is called once with it.
  351. * The supplied function is called with (Object item, Number index, Array allItems).
  352. * @param {Array/NodeList/Mixed} array
  353. * @param {Function} fn
  354. * @param {Object} scope
  355. */
  356. each : function(array, fn, scope){
  357. if(typeof array.length == "undefined" || typeof array == "string"){
  358. array = [array];
  359. }
  360. for(var i = 0, len = array.length; i < len; i++){
  361. if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
  362. }
  363. },
  364. // deprecated
  365. combine : function(){
  366. var as = arguments, l = as.length, r = [];
  367. for(var i = 0; i < l; i++){
  368. var a = as[i];
  369. if(Ext.isArray(a)){
  370. r = r.concat(a);
  371. }else if(a.length !== undefined && !a.substr){
  372. r = r.concat(Array.prototype.slice.call(a, 0));
  373. }else{
  374. r.push(a);
  375. }
  376. }
  377. return r;
  378. },
  379. /**
  380. * Escapes the passed string for use in a regular expression
  381. * @param {String} str
  382. * @return {String}
  383. */
  384. escapeRe : function(s) {
  385. return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
  386. },
  387. // internal
  388. callback : function(cb, scope, args, delay){
  389. if(typeof cb == "function"){
  390. if(delay){
  391. cb.defer(delay, scope, args || []);
  392. }else{
  393. cb.apply(scope, args || []);
  394. }
  395. }
  396. },
  397. /**
  398. * Return the dom node for the passed string (id), dom node, or Ext.Element
  399. * @param {Mixed} el
  400. * @return HTMLElement
  401. */
  402. getDom : function(el){
  403. if(!el || !document){
  404. return null;
  405. }
  406. return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
  407. },
  408. /**
  409. * Returns the current HTML document object as an {@link Ext.Element}.
  410. * @return Ext.Element The document
  411. */
  412. getDoc : function(){
  413. return Ext.get(document);
  414. },
  415. /**
  416. * Returns the current document body as an {@link Ext.Element}.
  417. * @return Ext.Element The document body
  418. */
  419. getBody : function(){
  420. return Ext.get(document.body || document.documentElement);
  421. },
  422. /**
  423. * Shorthand for {@link Ext.ComponentMgr#get}
  424. * @param {String} id
  425. * @return Ext.Component
  426. */
  427. getCmp : function(id){
  428. return Ext.ComponentMgr.get(id);
  429. },
  430. /**
  431. * Utility method for validating that a value is numeric, returning the specified default value if it is not.
  432. * @param {Mixed} value Should be a number, but any type will be handled appropriately
  433. * @param {Number} defaultValue The value to return if the original value is non-numeric
  434. * @return {Number} Value, if numeric, else defaultValue
  435. */
  436. num : function(v, defaultValue){
  437. if(typeof v != 'number'){
  438. return defaultValue;
  439. }
  440. return v;
  441. },
  442. /**
  443. * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
  444. * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
  445. * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
  446. * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
  447. * passed into this function in a single call as separate arguments.
  448. * @param {Mixed} arg1 An {@link Ext.Element} or {@link Ext.Component} to destroy
  449. * @param {Mixed} arg2 (optional)
  450. * @param {Mixed} etc... (optional)
  451. */
  452. destroy : function(){
  453. for(var i = 0, a = arguments, len = a.length; i < len; i++) {
  454. var as = a[i];
  455. if(as){
  456. if(typeof as.destroy == 'function'){
  457. as.destroy();
  458. }
  459. else if(as.dom){
  460. as.removeAllListeners();
  461. as.remove();
  462. }
  463. }
  464. }
  465. },
  466. /**
  467. * Removes a DOM node from the document. The body node will be ignored if passed in.
  468. * @param {HTMLElement} node The node to remove
  469. */
  470. removeNode : isIE ? function(){
  471. var d;
  472. return function(n){
  473. if(n && n.tagName != 'BODY'){
  474. d = d || document.createElement('div');
  475. d.appendChild(n);
  476. d.innerHTML = '';
  477. }
  478. }
  479. }() : function(n){
  480. if(n && n.parentNode && n.tagName != 'BODY'){
  481. n.parentNode.removeChild(n);
  482. }
  483. },
  484. // inpired by a similar function in mootools library
  485. /**
  486. * Returns the type of object that is passed in. If the object passed in is null or undefined it
  487. * return false otherwise it returns one of the following values:<ul>
  488. * <li><b>string</b>: If the object passed is a string</li>
  489. * <li><b>number</b>: If the object passed is a number</li>
  490. * <li><b>boolean</b>: If the object passed is a boolean value</li>
  491. * <li><b>function</b>: If the object passed is a function reference</li>
  492. * <li><b>object</b>: If the object passed is an object</li>
  493. * <li><b>array</b>: If the object passed is an array</li>
  494. * <li><b>regexp</b>: If the object passed is a regular expression</li>
  495. * <li><b>element</b>: If the object passed is a DOM Element</li>
  496. * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
  497. * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
  498. * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
  499. * @param {Mixed} object
  500. * @return {String}
  501. */
  502. type : function(o){
  503. if(o === undefined || o === null){
  504. return false;
  505. }
  506. if(o.htmlElement){
  507. return 'element';
  508. }
  509. var t = typeof o;
  510. if(t == 'object' && o.nodeName) {
  511. switch(o.nodeType) {
  512. case 1: return 'element';
  513. case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
  514. }
  515. }
  516. if(t == 'object' || t == 'function') {
  517. switch(o.constructor) {
  518. case Array: return 'array';
  519. case RegExp: return 'regexp';
  520. }
  521. if(typeof o.length == 'number' && typeof o.item == 'function') {
  522. return 'nodelist';
  523. }
  524. }
  525. return t;
  526. },
  527. /**
  528. * Returns true if the passed value is null, undefined or an empty string (optional).
  529. * @param {Mixed} value The value to test
  530. * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
  531. * @return {Boolean}
  532. */
  533. isEmpty : function(v, allowBlank){
  534. return v === null || v === undefined || (!allowBlank ? v === '' : false);
  535. },
  536. value : function(v, defaultValue, allowBlank){
  537. return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
  538. },
  539. /**
  540. * Returns true if the passed object is a JavaScript array, otherwise false.
  541. * @param {Object} The object to test
  542. * @return {Boolean}
  543. */
  544. isArray : function(v){
  545. return v && typeof v.length == 'number' && typeof v.splice == 'function';
  546. },
  547. /**
  548. * Returns true if the passed object is a JavaScript date object, otherwise false.
  549. * @param {Object} The object to test
  550. * @return {Boolean}
  551. */
  552. isDate : function(v){
  553. return v && typeof v.getFullYear == 'function';
  554. },
  555. /**
  556. * True if the detected browser is Opera.
  557. * @type Boolean
  558. */
  559. isOpera : isOpera,
  560. /**
  561. * True if the detected browser is Safari.
  562. * @type Boolean
  563. */
  564. isSafari : isSafari,
  565. /**
  566. * True if the detected browser is Safari 3.x.
  567. * @type Boolean
  568. */
  569. isSafari3 : isSafari3,
  570. /**
  571. * True if the detected browser is Safari 2.x.
  572. * @type Boolean
  573. */
  574. isSafari2 : isSafari && !isSafari3,
  575. /**
  576. * True if the detected browser is Internet Explorer.
  577. * @type Boolean
  578. */
  579. isIE : isIE,
  580. /**
  581. * True if the detected browser is Internet Explorer 6.x.
  582. * @type Boolean
  583. */
  584. isIE6 : isIE && !isIE7,
  585. /**
  586. * True if the detected browser is Internet Explorer 7.x.
  587. * @type Boolean
  588. */
  589. isIE7 : isIE7,
  590. /**
  591. * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
  592. * @type Boolean
  593. */
  594. isGecko : isGecko,
  595. /**
  596. * True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x).
  597. * @type Boolean
  598. */
  599. isGecko2 : isGecko && !isGecko3,
  600. /**
  601. * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
  602. * @type Boolean
  603. */
  604. isGecko3 : isGecko3,
  605. /**
  606. * True if the detected browser is Internet Explorer running in non-strict mode.
  607. * @type Boolean
  608. */
  609. isBorderBox : isBorderBox,
  610. /**
  611. * True if the detected platform is Linux.
  612. * @type Boolean
  613. */
  614. isLinux : isLinux,
  615. /**
  616. * True if the detected platform is Windows.
  617. * @type Boolean
  618. */
  619. isWindows : isWindows,
  620. /**
  621. * True if the detected platform is Mac OS.
  622. * @type Boolean
  623. */
  624. isMac : isMac,
  625. /**
  626. * True if the detected platform is Adobe Air.
  627. * @type Boolean
  628. */
  629. isAir : isAir,
  630. /**
  631. * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
  632. * you may want to set this to true.
  633. * @type Boolean
  634. */
  635. useShims : ((isIE && !isIE7) || (isMac && isGecko && !isGecko3))
  636. });
  637. // in intellij using keyword "namespace" causes parsing errors
  638. Ext.ns = Ext.namespace;
  639. })();
  640. Ext.ns("Ext", "Ext.util", "Ext.grid", "Ext.dd", "Ext.tree", "Ext.data",
  641. "Ext.form", "Ext.menu", "Ext.state", "Ext.lib", "Ext.layout", "Ext.app", "Ext.ux");
  642. /**
  643. * @class Function
  644. * These functions are available on every Function object (any JavaScript function).
  645. */
  646. Ext.apply(Function.prototype, {
  647. /**
  648. * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
  649. * Call directly on any function. Example: <code>myFunction.createCallback(arg1, arg2)</code>
  650. * Will create a function that is bound to those 2 args. <b>If a specific scope is required in the
  651. * callback, use {@link #createDelegate} instead.</b> The function returned by createCallback always
  652. * executes in the window scope.
  653. * <p>This method is required when you want to pass arguments to a callback function. If no arguments
  654. * are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn).
  655. * However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function
  656. * would simply execute immediately when the code is parsed. Example usage:
  657. * <pre><code>
  658. var sayHi = function(name){
  659. alert('Hi, ' + name);
  660. }
  661. // clicking the button alerts "Hi, Fred"
  662. new Ext.Button({
  663. text: 'Say Hi',
  664. renderTo: Ext.getBody(),
  665. handler: sayHi.createCallback('Fred')
  666. });
  667. </code></pre>
  668. * @return {Function} The new function
  669. */
  670. createCallback : function(/*args...*/){
  671. // make args available, in function below
  672. var args = arguments;
  673. var method = this;
  674. return function() {
  675. return method.apply(window, args);
  676. };
  677. },
  678. /**
  679. * Creates a delegate (callback) that sets the scope to obj.
  680. * Call directly on any function. Example: <code>this.myFunction.createDelegate(this, [arg1, arg2])</code>
  681. * Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the
  682. * callback points to obj. Example usage:
  683. * <pre><code>
  684. var sayHi = function(name){
  685. // Note this use of "this.text" here. This function expects to
  686. // execute within a scope that contains a text property. In this
  687. // example, the "this" variable is pointing to the btn object that
  688. // was passed in createDelegate below.
  689. alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.');
  690. }
  691. var btn = new Ext.Button({
  692. text: 'Say Hi',
  693. renderTo: Ext.getBody()
  694. });
  695. // This callback will execute in the scope of the
  696. // button instance. Clicking the button alerts
  697. // "Hi, Fred. You clicked the "Say Hi" button."
  698. btn.on('click', sayHi.createDelegate(btn, ['Fred']));
  699. </code></pre>
  700. * @param {Object} obj (optional) The object for which the scope is set
  701. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  702. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  703. * if a number the args are inserted at the specified position
  704. * @return {Function} The new function
  705. */
  706. createDelegate : function(obj, args, appendArgs){
  707. var method = this;
  708. return function() {
  709. var callArgs = args || arguments;
  710. if(appendArgs === true){
  711. callArgs = Array.prototype.slice.call(arguments, 0);
  712. callArgs = callArgs.concat(args);
  713. }else if(typeof appendArgs == "number"){
  714. callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
  715. var applyArgs = [appendArgs, 0].concat(args); // create method call params
  716. Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
  717. }
  718. return method.apply(obj || window, callArgs);
  719. };
  720. },
  721. /**
  722. * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
  723. * <pre><code>
  724. var sayHi = function(name){
  725. alert('Hi, ' + name);
  726. }
  727. // executes immediately:
  728. sayHi('Fred');
  729. // executes after 2 seconds:
  730. sayHi.defer(2000, this, ['Fred']);
  731. // this syntax is sometimes useful for deferring
  732. // execution of an anonymous function:
  733. (function(){
  734. alert('Anonymous');
  735. }).defer(100);
  736. </code></pre>
  737. * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
  738. * @param {Object} obj (optional) The object for which the scope is set
  739. * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
  740. * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
  741. * if a number the args are inserted at the specified position
  742. * @return {Number} The timeout id that can be used with clearTimeout
  743. */
  744. defer : function(millis, obj, args, appendArgs){
  745. var fn = this.createDelegate(obj, args, appendArgs);
  746. if(millis){
  747. return setTimeout(fn, millis);
  748. }
  749. fn();
  750. return 0;
  751. },
  752. /**
  753. * Create a combined function call sequence of the original function + the passed function.
  754. * The resulting function returns the results of the original function.
  755. * The passed fcn is called with the parameters of the original function. Example usage:
  756. * <pre><code>
  757. var sayHi = function(name){
  758. alert('Hi, ' + name);
  759. }
  760. sayHi('Fred'); // alerts "Hi, Fred"
  761. var sayGoodbye = sayHi.createSequence(function(name){
  762. alert('Bye, ' + name);
  763. });
  764. sayGoodbye('Fred'); // both alerts show
  765. </code></pre>
  766. * @param {Function} fcn The function to sequence
  767. * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
  768. * @return {Function} The new function
  769. */
  770. createSequence : function(fcn, scope){
  771. if(typeof fcn != "function"){
  772. return this;
  773. }
  774. var method = this;
  775. return function() {
  776. var retval = method.apply(this || window, arguments);
  777. fcn.apply(scope || this || window, arguments);
  778. return retval;
  779. };
  780. },
  781. /**
  782. * Creates an interceptor function. The passed fcn is called before the original one. If it returns false,
  783. * the original one is not called. The resulting function returns the results of the original function.
  784. * The passed fcn is called with the parameters of the original function. Example usage:
  785. * <pre><code>
  786. var sayHi = function(name){
  787. alert('Hi, ' + name);
  788. }
  789. sayHi('Fred'); // alerts "Hi, Fred"
  790. // create a new function that validates input without
  791. // directly modifying the original function:
  792. var sayHiToFriend = sayHi.createInterceptor(function(name){
  793. return name == 'Brian';
  794. });
  795. sayHiToFriend('Fred'); // no alert
  796. sayHiToFriend('Brian'); // alerts "Hi, Brian"
  797. </code></pre>
  798. * @param {Function} fcn The function to call before the original
  799. * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
  800. * @return {Function} The new function
  801. */
  802. createInterceptor : function(fcn, scope){
  803. if(typeof fcn != "function"){
  804. return this;
  805. }
  806. var method = this;
  807. return function() {
  808. fcn.target = this;
  809. fcn.method = method;
  810. if(fcn.apply(scope || this || window, arguments) === false){
  811. return;
  812. }
  813. return method.apply(this || window, arguments);
  814. };
  815. }
  816. });
  817. /**
  818. * @class String
  819. * These functions are available as static methods on the JavaScript String object.
  820. */
  821. Ext.applyIf(String, {
  822. /**
  823. * Escapes the passed string for ' and \
  824. * @param {String} string The string to escape
  825. * @return {String} The escaped string
  826. * @static
  827. */
  828. escape : function(string) {
  829. return string.replace(/('|\\)/g, "\\$1");
  830. },
  831. /**
  832. * Pads the left side of a string with a specified character. This is especially useful
  833. * for normalizing number and date strings. Example usage:
  834. * <pre><code>
  835. var s = String.leftPad('123', 5, '0');
  836. // s now contains the string: '00123'
  837. </code></pre>
  838. * @param {String} string The original string
  839. * @param {Number} size The total length of the output string
  840. * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
  841. * @return {String} The padded string
  842. * @static
  843. */
  844. leftPad : function (val, size, ch) {
  845. var result = new String(val);
  846. if(!ch) {
  847. ch = " ";
  848. }
  849. while (result.length < size) {
  850. result = ch + result;
  851. }
  852. return result.toString();
  853. },
  854. /**
  855. * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
  856. * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
  857. * <pre><code>
  858. var cls = 'my-class', text = 'Some text';
  859. var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
  860. // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
  861. </code></pre>
  862. * @param {String} string The tokenized string to be formatted
  863. * @param {String} value1 The value to replace token {0}
  864. * @param {String} value2 Etc...
  865. * @return {String} The formatted string
  866. * @static
  867. */
  868. format : function(format){
  869. var args = Array.prototype.slice.call(arguments, 1);
  870. return format.replace(/\{(\d+)\}/g, function(m, i){
  871. return args[i];
  872. });
  873. }
  874. });
  875. /**
  876. * Utility function that allows you to easily switch a string between two alternating values. The passed value
  877. * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
  878. * they are already different, the first value passed in is returned. Note that this method returns the new value
  879. * but does not change the current string.
  880. * <pre><code>
  881. // alternate sort directions
  882. sort = sort.toggle('ASC', 'DESC');
  883. // instead of conditional logic:
  884. sort = (sort == 'ASC' ? 'DESC' : 'ASC');
  885. </code></pre>
  886. * @param {String} value The value to compare to the current string
  887. * @param {String} other The new value to use if the string already equals the first value passed in
  888. * @return {String} The new value
  889. */
  890. String.prototype.toggle = function(value, other){
  891. return this == value ? other : value;
  892. };
  893. /**
  894. * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
  895. * <pre><code>
  896. var s = ' foo bar ';
  897. alert('-' + s + '-'); //alerts "- foo bar -"
  898. alert('-' + s.trim() + '-'); //alerts "-foo bar-"
  899. </code></pre>
  900. * @return {String} The trimmed string
  901. */
  902. String.prototype.trim = function(){
  903. var re = /^\s+|\s+$/g;
  904. return function(){ return this.replace(re, ""); };
  905. }();
  906. /**
  907. * @class Number
  908. */
  909. Ext.applyIf(Number.prototype, {
  910. /**
  911. * Checks whether or not the current number is within a desired range. If the number is already within the
  912. * range it is returned, otherwise the min or max value is returned depending on which side of the range is
  913. * exceeded. Note that this method returns the constrained value but does not change the current number.
  914. * @param {Number} min The minimum number in the range
  915. * @param {Number} max The maximum number in the range
  916. * @return {Number} The constrained value if outside the range, otherwise the current value
  917. */
  918. constrain : function(min, max){
  919. return Math.min(Math.max(this, min), max);
  920. }
  921. });
  922. /**
  923. * @class Array
  924. */
  925. Ext.applyIf(Array.prototype, {
  926. /**
  927. * Checks whether or not the specified object exists in the array.
  928. * @param {Object} o The object to check for
  929. * @return {Number} The index of o in the array (or -1 if it is not found)
  930. */
  931. indexOf : function(o){
  932. for (var i = 0, len = this.length; i < len; i++){
  933. if(this[i] == o) return i;
  934. }
  935. return -1;
  936. },
  937. /**
  938. * Removes the specified object from the array. If the object is not found nothing happens.
  939. * @param {Object} o The object to remove
  940. * @return {Array} this array
  941. */
  942. remove : function(o){
  943. var index = this.indexOf(o);
  944. if(index != -1){
  945. this.splice(index, 1);
  946. }
  947. return this;
  948. }
  949. });
  950. /**
  951. Returns the number of milliseconds between this date and date
  952. @param {Date} date (optional) Defaults to now
  953. @return {Number} The diff in milliseconds
  954. @member Date getElapsed
  955. */
  956. Date.prototype.getElapsed = function(date) {
  957. return Math.abs((date || new Date()).getTime()-this.getTime());
  958. };