2 Ext JS - JavaScript Library
3 Copyright (c) 2006-2011, Sencha Inc.
13 objectPrototype = Object.prototype,
14 toString = Object.prototype.toString,
16 enumerablesTest = { toString: 1 },
19 if (typeof Ext === 'undefined') {
25 for (i in enumerablesTest) {
30 enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
31 'toLocaleString', 'toString', 'constructor'];
35 * An array containing extra enumerables for old browsers
38 Ext.enumerables = enumerables;
41 * Copies all the properties of config to the specified object.
42 * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
43 * {@link Ext.Object#merge} instead.
44 * @param {Object} object The receiver of the properties
45 * @param {Object} config The source of the properties
46 * @param {Object} defaults A different object that will also be applied for default values
47 * @return {Object} returns obj
49 Ext.apply = function(object, config, defaults) {
51 Ext.apply(object, defaults);
54 if (object && config && typeof config === 'object') {
58 object[i] = config[i];
62 for (j = enumerables.length; j--;) {
64 if (config.hasOwnProperty(k)) {
65 object[k] = config[k];
74 Ext.buildSettings = Ext.apply({
77 }, Ext.buildSettings || {});
81 * A reusable empty function
83 emptyFn: function() {},
85 baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
88 * Copies all the properties of config to object if they don't already exist.
90 * @param {Object} object The receiver of the properties
91 * @param {Object} config The source of the properties
92 * @return {Object} returns obj
94 applyIf: function(object, config) {
98 for (property in config) {
99 if (object[property] === undefined) {
100 object[property] = config[property];
109 * Iterates either an array or an object. This method delegates to
110 * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
112 * @param {Object/Array} object The object or array to be iterated.
113 * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
114 * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
115 * type that is being iterated.
116 * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
117 * Defaults to the object being iterated itself.
120 iterate: function(object, fn, scope) {
121 if (Ext.isEmpty(object)) {
125 if (scope === undefined) {
129 if (Ext.isIterable(object)) {
130 Ext.Array.each.call(Ext.Array, object, fn, scope);
133 Ext.Object.each.call(Ext.Object, object, fn, scope);
141 * This method deprecated. Use {@link Ext#define Ext.define} instead.
143 * @param {Function} superclass
144 * @param {Object} overrides
145 * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
146 * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
150 var objectConstructor = objectPrototype.constructor,
151 inlineOverrides = function(o) {
153 if (!o.hasOwnProperty(m)) {
160 return function(subclass, superclass, overrides) {
161 // First we check if the user passed in just the superClass with overrides
162 if (Ext.isObject(superclass)) {
163 overrides = superclass;
164 superclass = subclass;
165 subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
166 superclass.apply(this, arguments);
173 sourceMethod: 'extend',
174 msg: 'Attempting to extend from a class which has not been loaded on the page.'
178 // We create a new temporary class
179 var F = function() {},
180 subclassProto, superclassProto = superclass.prototype;
182 F.prototype = superclassProto;
183 subclassProto = subclass.prototype = new F();
184 subclassProto.constructor = subclass;
185 subclass.superclass = superclassProto;
187 if (superclassProto.constructor === objectConstructor) {
188 superclassProto.constructor = superclass;
191 subclass.override = function(overrides) {
192 Ext.override(subclass, overrides);
195 subclassProto.override = inlineOverrides;
196 subclassProto.proto = subclassProto;
198 subclass.override(overrides);
199 subclass.extend = function(o) {
200 return Ext.extend(subclass, o);
208 * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
210 Ext.define('My.cool.Class', {
216 Ext.override(My.cool.Class, {
218 alert('About to say...');
220 this.callOverridden();
224 var cool = new My.cool.Class();
225 cool.sayHi(); // alerts 'About to say...'
228 * Please note that `this.callOverridden()` only works if the class was previously
229 * created with {@link Ext#define)
231 * @param {Object} cls The class to override
232 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
233 * containing one or more methods.
237 override: function(cls, overrides) {
238 if (cls.prototype.$className) {
239 return cls.override(overrides);
242 Ext.apply(cls.prototype, overrides);
247 // A full set of static methods to do type checking
251 * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
252 * value (second argument) otherwise.
254 * @param {Mixed} value The value to test
255 * @param {Mixed} defaultValue The value to return if the original value is empty
256 * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
257 * @return {Mixed} value, if non-empty, else defaultValue
259 valueFrom: function(value, defaultValue, allowBlank){
260 return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
264 * Returns the type of the given variable in string format. List of possible values are:
266 * - `undefined`: If the given value is `undefined`
267 * - `null`: If the given value is `null`
268 * - `string`: If the given value is a string
269 * - `number`: If the given value is a number
270 * - `boolean`: If the given value is a boolean value
271 * - `date`: If the given value is a `Date` object
272 * - `function`: If the given value is a function reference
273 * - `object`: If the given value is an object
274 * - `array`: If the given value is an array
275 * - `regexp`: If the given value is a regular expression
276 * - `element`: If the given value is a DOM Element
277 * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
278 * - `whitespace`: If the given value is a DOM text node and contains only whitespace
280 * @param {Mixed} value
284 typeOf: function(value) {
285 if (value === null) {
289 var type = typeof value;
291 if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
295 var typeToString = toString.call(value);
297 switch(typeToString) {
298 case '[object Array]':
300 case '[object Date]':
302 case '[object Boolean]':
304 case '[object Number]':
306 case '[object RegExp]':
310 if (type === 'function') {
314 if (type === 'object') {
315 if (value.nodeType !== undefined) {
316 if (value.nodeType === 3) {
317 return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
329 sourceMethod: 'typeOf',
330 msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
335 * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
339 * - a zero-length array
340 * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
342 * @param {Mixed} value The value to test
343 * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
347 isEmpty: function(value, allowEmptyString) {
348 return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
352 * Returns true if the passed value is a JavaScript Array, false otherwise.
354 * @param {Mixed} target The target to test
358 isArray: ('isArray' in Array) ? Array.isArray : function(value) {
359 return toString.call(value) === '[object Array]';
363 * Returns true if the passed value is a JavaScript Date object, false otherwise.
364 * @param {Object} object The object to test
367 isDate: function(value) {
368 return toString.call(value) === '[object Date]';
372 * Returns true if the passed value is a JavaScript Object, false otherwise.
373 * @param {Mixed} value The value to test
377 isObject: (toString.call(null) === '[object Object]') ?
379 return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.nodeType === undefined;
382 return toString.call(value) === '[object Object]';
386 * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
387 * @param {Mixed} value The value to test
390 isPrimitive: function(value) {
391 var type = typeof value;
393 return type === 'string' || type === 'number' || type === 'boolean';
397 * Returns true if the passed value is a JavaScript Function, false otherwise.
398 * @param {Mixed} value The value to test
403 // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
404 // Object.prorotype.toString (slower)
405 (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
406 return toString.call(value) === '[object Function]';
407 } : function(value) {
408 return typeof value === 'function';
412 * Returns true if the passed value is a number. Returns false for non-finite numbers.
413 * @param {Mixed} value The value to test
416 isNumber: function(value) {
417 return typeof value === 'number' && isFinite(value);
421 * Validates that a value is numeric.
422 * @param {Mixed} value Examples: 1, '1', '2.34'
423 * @return {Boolean} True if numeric, false otherwise
425 isNumeric: function(value) {
426 return !isNaN(parseFloat(value)) && isFinite(value);
430 * Returns true if the passed value is a string.
431 * @param {Mixed} value The value to test
434 isString: function(value) {
435 return typeof value === 'string';
439 * Returns true if the passed value is a boolean.
441 * @param {Mixed} value The value to test
444 isBoolean: function(value) {
445 return typeof value === 'boolean';
449 * Returns true if the passed value is an HTMLElement
450 * @param {Mixed} value The value to test
453 isElement: function(value) {
454 return value ? value.nodeType === 1 : false;
458 * Returns true if the passed value is a TextNode
459 * @param {Mixed} value The value to test
462 isTextNode: function(value) {
463 return value ? value.nodeName === "#text" : false;
467 * Returns true if the passed value is defined.
468 * @param {Mixed} value The value to test
471 isDefined: function(value) {
472 return typeof value !== 'undefined';
476 * Returns true if the passed value is iterable, false otherwise
477 * @param {Mixed} value The value to test
480 isIterable: function(value) {
481 return (value && typeof value !== 'string') ? value.length !== undefined : false;
488 * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
489 * @param {Mixed} item The variable to clone
490 * @return {Mixed} clone
492 clone: function(item) {
493 if (item === null || item === undefined) {
498 // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
500 if (item.nodeType && item.cloneNode) {
501 return item.cloneNode(true);
504 var type = toString.call(item);
507 if (type === '[object Date]') {
508 return new Date(item.getTime());
511 var i, j, k, clone, key;
514 if (type === '[object Array]') {
520 clone[i] = Ext.clone(item[i]);
524 else if (type === '[object Object]' && item.constructor === Object) {
528 clone[key] = Ext.clone(item[key]);
532 for (j = enumerables.length; j--;) {
539 return clone || item;
544 * Generate a unique reference of Ext in the global scope, useful for sandboxing
546 getUniqueGlobalNamespace: function() {
547 var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
549 if (uniqueGlobalNamespace === undefined) {
553 uniqueGlobalNamespace = 'ExtSandbox' + (++i);
554 } while (Ext.global[uniqueGlobalNamespace] !== undefined);
556 Ext.global[uniqueGlobalNamespace] = Ext;
557 this.uniqueGlobalNamespace = uniqueGlobalNamespace;
560 return uniqueGlobalNamespace;
566 functionFactory: function() {
567 var args = Array.prototype.slice.call(arguments);
569 if (args.length > 0) {
570 args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
571 args[args.length - 1];
574 return Function.prototype.constructor.apply(Function.prototype, args);
579 * Old alias to {@link Ext#typeOf}
580 * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
583 Ext.type = Ext.typeOf;
588 * @author Jacky Nguyen <jacky@sencha.com>
589 * @docauthor Jacky Nguyen <jacky@sencha.com>
592 * A utility class that wrap around a string version number and provide convenient
593 * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
595 var version = new Ext.Version('1.0.2beta');
596 console.log("Version is " + version); // Version is 1.0.2beta
598 console.log(version.getMajor()); // 1
599 console.log(version.getMinor()); // 0
600 console.log(version.getPatch()); // 2
601 console.log(version.getBuild()); // 0
602 console.log(version.getRelease()); // beta
604 console.log(version.isGreaterThan('1.0.1')); // True
605 console.log(version.isGreaterThan('1.0.2alpha')); // True
606 console.log(version.isGreaterThan('1.0.2RC')); // False
607 console.log(version.isGreaterThan('1.0.2')); // False
608 console.log(version.isLessThan('1.0.2')); // True
610 console.log(version.match(1.0)); // True
611 console.log(version.match('1.0.2')); // True
617 // Current core version
618 var version = '4.0.1', Version;
619 Ext.Version = Version = Ext.extend(Object, {
623 * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
624 * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
625 * @return {Ext.Version} this
628 constructor: function(version) {
629 var parts, releaseStartIndex;
631 if (version instanceof Version) {
635 this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
637 releaseStartIndex = this.version.search(/([^\d\.])/);
639 if (releaseStartIndex !== -1) {
640 this.release = this.version.substr(releaseStartIndex, version.length);
641 this.shortVersion = this.version.substr(0, releaseStartIndex);
644 this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
646 parts = this.version.split('.');
648 this.major = parseInt(parts.shift() || 0, 10);
649 this.minor = parseInt(parts.shift() || 0, 10);
650 this.patch = parseInt(parts.shift() || 0, 10);
651 this.build = parseInt(parts.shift() || 0, 10);
657 * Override the native toString method
659 * @return {String} version
661 toString: function() {
666 * Override the native valueOf method
668 * @return {String} version
670 valueOf: function() {
675 * Returns the major component value
676 * @return {Number} major
678 getMajor: function() {
679 return this.major || 0;
683 * Returns the minor component value
684 * @return {Number} minor
686 getMinor: function() {
687 return this.minor || 0;
691 * Returns the patch component value
692 * @return {Number} patch
694 getPatch: function() {
695 return this.patch || 0;
699 * Returns the build component value
700 * @return {Number} build
702 getBuild: function() {
703 return this.build || 0;
707 * Returns the release component value
708 * @return {Number} release
710 getRelease: function() {
711 return this.release || '';
715 * Returns whether this version if greater than the supplied argument
716 * @param {String/Number} target The version to compare with
717 * @return {Boolean} True if this version if greater than the target, false otherwise
719 isGreaterThan: function(target) {
720 return Version.compare(this.version, target) === 1;
724 * Returns whether this version if smaller than the supplied argument
725 * @param {String/Number} target The version to compare with
726 * @return {Boolean} True if this version if smaller than the target, false otherwise
728 isLessThan: function(target) {
729 return Version.compare(this.version, target) === -1;
733 * Returns whether this version equals to the supplied argument
734 * @param {String/Number} target The version to compare with
735 * @return {Boolean} True if this version equals to the target, false otherwise
737 equals: function(target) {
738 return Version.compare(this.version, target) === 0;
742 * Returns whether this version matches the supplied argument. Example:
744 * var version = new Ext.Version('1.0.2beta');
745 * console.log(version.match(1)); // True
746 * console.log(version.match(1.0)); // True
747 * console.log(version.match('1.0.2')); // True
748 * console.log(version.match('1.0.2RC')); // False
750 * @param {String/Number} target The version to compare with
751 * @return {Boolean} True if this version matches the target, false otherwise
753 match: function(target) {
754 target = String(target);
755 return this.version.substr(0, target.length) === target;
759 * Returns this format: [major, minor, patch, build, release]. Useful for comparison
762 toArray: function() {
763 return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
767 * Returns shortVersion version without dots and release
770 getShortVersion: function() {
771 return this.shortVersion;
790 * Converts a version component to a comparable value
793 * @param {Mixed} value The value to convert
796 getComponentValue: function(value) {
797 return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
801 * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
802 * they are handled in the following order:
803 * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
806 * @param {String} current The current version to compare to
807 * @param {String} target The target version to compare to
808 * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
810 compare: function(current, target) {
811 var currentValue, targetValue, i;
813 current = new Version(current).toArray();
814 target = new Version(target).toArray();
816 for (i = 0; i < Math.max(current.length, target.length); i++) {
817 currentValue = this.getComponentValue(current[i]);
818 targetValue = this.getComponentValue(target[i]);
820 if (currentValue < targetValue) {
822 } else if (currentValue > targetValue) {
840 lastRegisteredVersion: null,
843 * Set version number for the given package name.
845 * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
846 * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
849 setVersion: function(packageName, version) {
850 Ext.versions[packageName] = new Version(version);
851 Ext.lastRegisteredVersion = Ext.versions[packageName];
857 * Get the version number of the supplied package name; will return the last registered version
858 * (last Ext.setVersion call) if there's no package name given.
860 * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
861 * @return {Ext.Version} The version
863 getVersion: function(packageName) {
864 if (packageName === undefined) {
865 return Ext.lastRegisteredVersion;
868 return Ext.versions[packageName];
872 * Create a closure for deprecated code.
874 // This means Ext.oldMethod is only supported in 4.0.0beta and older.
875 // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
876 // the closure will not be invoked
877 Ext.deprecate('extjs', '4.0.0beta', function() {
878 Ext.oldMethod = Ext.newMethod;
883 * @param {String} packageName The package name
884 * @param {String} since The last version before it's deprecated
885 * @param {Function} closure The callback function to be executed with the specified version is less than the current version
886 * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
889 deprecate: function(packageName, since, closure, scope) {
890 if (Version.compare(Ext.getVersion(packageName), since) < 1) {
894 }); // End Versioning
896 Ext.setVersion('core', version);
903 * A collection of useful static methods to deal with strings
908 trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
910 formatRe: /\{(\d+)\}/g,
911 escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
914 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
915 * @param {String} value The string to encode
916 * @return {String} The encoded text
919 htmlEncode: (function() {
925 }, keys = [], p, regex;
927 for (p in entities) {
931 regex = new RegExp('(' + keys.join('|') + ')', 'g');
933 return function(value) {
934 return (!value) ? value : String(value).replace(regex, function(match, capture) {
935 return entities[capture];
941 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
942 * @param {String} value The string to decode
943 * @return {String} The decoded text
946 htmlDecode: (function() {
952 }, keys = [], p, regex;
954 for (p in entities) {
958 regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
960 return function(value) {
961 return (!value) ? value : String(value).replace(regex, function(match, capture) {
962 if (capture in entities) {
963 return entities[capture];
965 return String.fromCharCode(parseInt(capture.substr(2), 10));
972 * Appends content to the query string of a URL, handling logic for whether to place
973 * a question mark or ampersand.
974 * @param {String} url The URL to append to.
975 * @param {String} string The content to append to the URL.
976 * @return (String) The resulting URL
978 urlAppend : function(url, string) {
979 if (!Ext.isEmpty(string)) {
980 return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
987 * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
990 alert('-' + s + '-'); //alerts "- foo bar -"
991 alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
993 * @param {String} string The string to escape
994 * @return {String} The trimmed string
996 trim: function(string) {
997 return string.replace(Ext.String.trimRegex, "");
1001 * Capitalize the given string
1002 * @param {String} string
1005 capitalize: function(string) {
1006 return string.charAt(0).toUpperCase() + string.substr(1);
1010 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
1011 * @param {String} value The string to truncate
1012 * @param {Number} length The maximum length to allow before truncating
1013 * @param {Boolean} word True to try to find a common word break
1014 * @return {String} The converted text
1016 ellipsis: function(value, len, word) {
1017 if (value && value.length > len) {
1019 var vs = value.substr(0, len - 2),
1020 index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
1021 if (index !== -1 && index >= (len - 15)) {
1022 return vs.substr(0, index) + "...";
1025 return value.substr(0, len - 3) + "...";
1031 * Escapes the passed string for use in a regular expression
1032 * @param {String} string
1035 escapeRegex: function(string) {
1036 return string.replace(Ext.String.escapeRegexRe, "\\$1");
1040 * Escapes the passed string for ' and \
1041 * @param {String} string The string to escape
1042 * @return {String} The escaped string
1044 escape: function(string) {
1045 return string.replace(Ext.String.escapeRe, "\\$1");
1049 * Utility function that allows you to easily switch a string between two alternating values. The passed value
1050 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
1051 * they are already different, the first value passed in is returned. Note that this method returns the new value
1052 * but does not change the current string.
1054 // alternate sort directions
1055 sort = Ext.String.toggle(sort, 'ASC', 'DESC');
1057 // instead of conditional logic:
1058 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
1060 * @param {String} string The current string
1061 * @param {String} value The value to compare to the current string
1062 * @param {String} other The new value to use if the string already equals the first value passed in
1063 * @return {String} The new value
1065 toggle: function(string, value, other) {
1066 return string === value ? other : value;
1070 * Pads the left side of a string with a specified character. This is especially useful
1071 * for normalizing number and date strings. Example usage:
1074 var s = Ext.String.leftPad('123', 5, '0');
1075 // s now contains the string: '00123'
1077 * @param {String} string The original string
1078 * @param {Number} size The total length of the output string
1079 * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
1080 * @return {String} The padded string
1082 leftPad: function(string, size, character) {
1083 var result = String(string);
1084 character = character || " ";
1085 while (result.length < size) {
1086 result = character + result;
1092 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
1093 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
1095 var cls = 'my-class', text = 'Some text';
1096 var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
1097 // s now contains the string: '<div class="my-class">Some text</div>'
1099 * @param {String} string The tokenized string to be formatted
1100 * @param {String} value1 The value to replace token {0}
1101 * @param {String} value2 Etc...
1102 * @return {String} The formatted string
1104 format: function(format) {
1105 var args = Ext.Array.toArray(arguments, 1);
1106 return format.replace(Ext.String.formatRe, function(m, i) {
1115 * A collection of useful static methods to deal with numbers
1121 var isToFixedBroken = (0.9).toFixed() !== '1';
1125 * Checks whether or not the current number is within a desired range. If the number is already within the
1126 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
1127 * exceeded. Note that this method returns the constrained value but does not change the current number.
1128 * @param {Number} number The number to check
1129 * @param {Number} min The minimum number in the range
1130 * @param {Number} max The maximum number in the range
1131 * @return {Number} The constrained value if outside the range, otherwise the current value
1133 constrain: function(number, min, max) {
1134 number = parseFloat(number);
1137 number = Math.max(number, min);
1140 number = Math.min(number, max);
1146 * Formats a number using fixed-point notation
1147 * @param {Number} value The number to format
1148 * @param {Number} precision The number of digits to show after the decimal point
1150 toFixed: function(value, precision) {
1151 if (isToFixedBroken) {
1152 precision = precision || 0;
1153 var pow = Math.pow(10, precision);
1154 return (Math.round(value * pow) / pow).toFixed(precision);
1157 return value.toFixed(precision);
1161 * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
1164 Ext.Number.from('1.23', 1); // returns 1.23
1165 Ext.Number.from('abc', 1); // returns 1
1167 * @param {Mixed} value
1168 * @param {Number} defaultValue The value to return if the original value is non-numeric
1169 * @return {Number} value, if numeric, defaultValue otherwise
1171 from: function(value, defaultValue) {
1172 if (isFinite(value)) {
1173 value = parseFloat(value);
1176 return !isNaN(value) ? value : defaultValue;
1183 * This method is deprecated, please use {@link Ext.Number#from Ext.Number.from} instead
1185 * @deprecated 4.0.0 Replaced by Ext.Number.from
1189 Ext.num = function() {
1190 return Ext.Number.from.apply(this, arguments);
1193 * @author Jacky Nguyen <jacky@sencha.com>
1194 * @docauthor Jacky Nguyen <jacky@sencha.com>
1197 * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
1204 var arrayPrototype = Array.prototype,
1205 slice = arrayPrototype.slice,
1206 supportsForEach = 'forEach' in arrayPrototype,
1207 supportsMap = 'map' in arrayPrototype,
1208 supportsIndexOf = 'indexOf' in arrayPrototype,
1209 supportsEvery = 'every' in arrayPrototype,
1210 supportsSome = 'some' in arrayPrototype,
1211 supportsFilter = 'filter' in arrayPrototype,
1212 supportsSort = function() {
1213 var a = [1,2,3,4,5].sort(function(){ return 0; });
1214 return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
1216 supportsSliceOnNodeList = true,
1219 // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
1220 if (typeof document !== 'undefined') {
1221 slice.call(document.getElementsByTagName('body'));
1224 supportsSliceOnNodeList = false;
1227 ExtArray = Ext.Array = {
1229 * Iterates an array or an iterable value and invoke the given callback function for each item.
1231 var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
1233 Ext.Array.each(countries, function(name, index, countriesItSelf) {
1237 var sum = function() {
1240 Ext.Array.each(arguments, function(value) {
1247 sum(1, 2, 3); // returns 6
1249 * The iteration can be stopped by returning false in the function callback.
1251 Ext.Array.each(countries, function(name, index, countriesItSelf) {
1252 if (name === 'Singapore') {
1253 return false; // break here
1257 * @param {Array/NodeList/Mixed} iterable The value to be iterated. If this
1258 * argument is not iterable, the callback function is called once.
1259 * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
1260 * the current `index`. Arguments passed to this callback function are:
1262 - `item`: {Mixed} The item at the current `index` in the passed `array`
1263 - `index`: {Number} The current `index` within the `array`
1264 - `allItems`: {Array/NodeList/Mixed} The `array` passed as the first argument to `Ext.Array.each`
1266 * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
1267 * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
1269 * @return {Boolean} See description for the `fn` parameter.
1272 each: function(array, fn, scope, reverse) {
1273 array = ExtArray.from(array);
1278 if (reverse !== true) {
1279 for (i = 0; i < ln; i++) {
1280 if (fn.call(scope || array[i], array[i], i, array) === false) {
1286 for (i = ln - 1; i > -1; i--) {
1287 if (fn.call(scope || array[i], array[i], i, array) === false) {
1297 * Iterates an array and invoke the given callback function for each item. Note that this will simply
1298 * delegate to the native Array.prototype.forEach method if supported.
1299 * It doesn't support stopping the iteration by returning false in the callback function like
1300 * {@link Ext.Array#each}. However, performance could be much better in modern browsers comparing with
1301 * {@link Ext.Array#each}
1303 * @param {Array} array The array to iterate
1304 * @param {Function} fn The function callback, to be invoked these arguments:
1306 - `item`: {Mixed} The item at the current `index` in the passed `array`
1307 - `index`: {Number} The current `index` within the `array`
1308 - `allItems`: {Array} The `array` itself which was passed as the first argument
1310 * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
1313 forEach: function(array, fn, scope) {
1314 if (supportsForEach) {
1315 return array.forEach(fn, scope);
1321 for (; i < ln; i++) {
1322 fn.call(scope, array[i], i, array);
1327 * Get the index of the provided `item` in the given `array`, a supplement for the
1328 * missing arrayPrototype.indexOf in Internet Explorer.
1330 * @param {Array} array The array to check
1331 * @param {Mixed} item The item to look for
1332 * @param {Number} from (Optional) The index at which to begin the search
1333 * @return {Number} The index of item in the array (or -1 if it is not found)
1336 indexOf: function(array, item, from) {
1337 if (supportsIndexOf) {
1338 return array.indexOf(item, from);
1341 var i, length = array.length;
1343 for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
1344 if (array[i] === item) {
1353 * Checks whether or not the given `array` contains the specified `item`
1355 * @param {Array} array The array to check
1356 * @param {Mixed} item The item to look for
1357 * @return {Boolean} True if the array contains the item, false otherwise
1360 contains: function(array, item) {
1361 if (supportsIndexOf) {
1362 return array.indexOf(item) !== -1;
1367 for (i = 0, ln = array.length; i < ln; i++) {
1368 if (array[i] === item) {
1377 * Converts any iterable (numeric indices and a length property) into a true array.
1380 var args = Ext.Array.toArray(arguments),
1381 fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
1383 alert(args.join(' '));
1384 alert(fromSecondToLastArgs.join(' '));
1387 test('just', 'testing', 'here'); // alerts 'just testing here';
1388 // alerts 'testing here';
1390 Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
1391 Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
1392 Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
1394 * @param {Mixed} iterable the iterable object to be turned into a true Array.
1395 * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
1396 * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
1397 * index of the iterable value
1398 * @return {Array} array
1401 toArray: function(iterable, start, end){
1402 if (!iterable || !iterable.length) {
1406 if (typeof iterable === 'string') {
1407 iterable = iterable.split('');
1410 if (supportsSliceOnNodeList) {
1411 return slice.call(iterable, start || 0, end || iterable.length);
1418 end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
1420 for (i = start; i < end; i++) {
1421 array.push(iterable[i]);
1428 * Plucks the value of a property from each item in the Array. Example:
1430 Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
1432 * @param {Array|NodeList} array The Array of items to pluck the value from.
1433 * @param {String} propertyName The property name to pluck from each element.
1434 * @return {Array} The value from each item in the Array.
1436 pluck: function(array, propertyName) {
1440 for (i = 0, ln = array.length; i < ln; i++) {
1443 ret.push(item[propertyName]);
1450 * Creates a new array with the results of calling a provided function on every element in this array.
1451 * @param {Array} array
1452 * @param {Function} fn Callback function for each item
1453 * @param {Object} scope Callback function scope
1454 * @return {Array} results
1456 map: function(array, fn, scope) {
1458 return array.map(fn, scope);
1465 for (; i < len; i++) {
1466 results[i] = fn.call(scope, array[i], i, array);
1473 * Executes the specified function for each array element until the function returns a falsy value.
1474 * If such an item is found, the function will return false immediately.
1475 * Otherwise, it will return true.
1477 * @param {Array} array
1478 * @param {Function} fn Callback function for each item
1479 * @param {Object} scope Callback function scope
1480 * @return {Boolean} True if no false value is returned by the callback function.
1482 every: function(array, fn, scope) {
1484 Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
1486 if (supportsEvery) {
1487 return array.every(fn, scope);
1493 for (; i < ln; ++i) {
1494 if (!fn.call(scope, array[i], i, array)) {
1503 * Executes the specified function for each array element until the function returns a truthy value.
1504 * If such an item is found, the function will return true immediately. Otherwise, it will return false.
1506 * @param {Array} array
1507 * @param {Function} fn Callback function for each item
1508 * @param {Object} scope Callback function scope
1509 * @return {Boolean} True if the callback function returns a truthy value.
1511 some: function(array, fn, scope) {
1513 Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
1516 return array.some(fn, scope);
1522 for (; i < ln; ++i) {
1523 if (fn.call(scope, array[i], i, array)) {
1532 * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
1534 * @see Ext.Array.filter
1535 * @param {Array} array
1536 * @return {Array} results
1538 clean: function(array) {
1544 for (; i < ln; i++) {
1547 if (!Ext.isEmpty(item)) {
1556 * Returns a new array with unique items
1558 * @param {Array} array
1559 * @return {Array} results
1561 unique: function(array) {
1567 for (; i < ln; i++) {
1570 if (ExtArray.indexOf(clone, item) === -1) {
1579 * Creates a new array with all of the elements of this array for which
1580 * the provided filtering function returns true.
1581 * @param {Array} array
1582 * @param {Function} fn Callback function for each item
1583 * @param {Object} scope Callback function scope
1584 * @return {Array} results
1586 filter: function(array, fn, scope) {
1587 if (supportsFilter) {
1588 return array.filter(fn, scope);
1595 for (; i < ln; i++) {
1596 if (fn.call(scope, array[i], i, array)) {
1597 results.push(array[i]);
1605 * Converts a value to an array if it's not already an array; returns:
1607 * - An empty array if given value is `undefined` or `null`
1608 * - Itself if given value is already an array
1609 * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
1610 * - An array with one item which is the given value, otherwise
1612 * @param {Array/Mixed} value The value to convert to an array if it's not already is an array
1613 * @param {Boolean} (Optional) newReference True to clone the given array and return a new reference if necessary,
1615 * @return {Array} array
1618 from: function(value, newReference) {
1619 if (value === undefined || value === null) {
1623 if (Ext.isArray(value)) {
1624 return (newReference) ? slice.call(value) : value;
1627 if (value && value.length !== undefined && typeof value !== 'string') {
1628 return Ext.toArray(value);
1635 * Removes the specified item from the array if it exists
1637 * @param {Array} array The array
1638 * @param {Mixed} item The item to remove
1639 * @return {Array} The passed array itself
1641 remove: function(array, item) {
1642 var index = ExtArray.indexOf(array, item);
1645 array.splice(index, 1);
1652 * Push an item into the array only if the array doesn't contain it yet
1654 * @param {Array} array The array
1655 * @param {Mixed} item The item to include
1656 * @return {Array} The passed array itself
1658 include: function(array, item) {
1659 if (!ExtArray.contains(array, item)) {
1665 * Clone a flat array without referencing the previous one. Note that this is different
1666 * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
1667 * for Array.prototype.slice.call(array)
1669 * @param {Array} array The array
1670 * @return {Array} The clone array
1672 clone: function(array) {
1673 return slice.call(array);
1677 * Merge multiple arrays into one with unique items. Alias to {@link Ext.Array#union}.
1679 * @param {Array} array,...
1680 * @return {Array} merged
1683 var args = slice.call(arguments),
1687 for (i = 0, ln = args.length; i < ln; i++) {
1688 array = array.concat(args[i]);
1691 return ExtArray.unique(array);
1695 * Merge multiple arrays into one with unique items that exist in all of the arrays.
1697 * @param {Array} array,...
1698 * @return {Array} intersect
1700 intersect: function() {
1702 arrays = slice.call(arguments),
1703 i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
1705 if (!arrays.length) {
1709 // Find the smallest array
1710 for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
1711 if (!minArray || array.length < minArray.length) {
1717 minArray = Ext.Array.unique(minArray);
1718 arrays.splice(x, 1);
1720 // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
1721 // an item in the small array, we're likely to find it before reaching the end
1722 // of the inner loop and can terminate the search early.
1723 for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
1726 for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
1727 for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
1735 if (count === arraysLn) {
1744 * Perform a set difference A-B by subtracting all items in array B from array A.
1746 * @param {Array} array A
1747 * @param {Array} array B
1748 * @return {Array} difference
1750 difference: function(arrayA, arrayB) {
1751 var clone = slice.call(arrayA),
1755 for (i = 0,lnB = arrayB.length; i < lnB; i++) {
1756 for (j = 0; j < ln; j++) {
1757 if (clone[j] === arrayB[i]) {
1769 * Sorts the elements of an Array.
1770 * By default, this method sorts the elements alphabetically and ascending.
1772 * @param {Array} array The array to sort.
1773 * @param {Function} sortFn (optional) The comparison function.
1774 * @return {Array} The sorted array.
1776 sort: function(array, sortFn) {
1779 return array.sort(sortFn);
1781 return array.sort();
1785 var length = array.length,
1790 for (; i < length; i++) {
1792 for (j = i + 1; j < length; j++) {
1794 comparison = sortFn(array[j], array[min]);
1795 if (comparison < 0) {
1798 } else if (array[j] < array[min]) {
1804 array[i] = array[min];
1813 * Recursively flattens into 1-d Array. Injects Arrays inline.
1814 * @param {Array} array The array to flatten
1815 * @return {Array} The new, flattened array.
1817 flatten: function(array) {
1820 function rFlatten(a) {
1823 for (i = 0, ln = a.length; i < ln; i++) {
1826 if (Ext.isArray(v)) {
1836 return rFlatten(array);
1840 * Returns the minimum value in the Array.
1841 * @param {Array|NodeList} array The Array from which to select the minimum value.
1842 * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
1843 * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
1844 * @return {Mixed} minValue The minimum value
1846 min: function(array, comparisonFn) {
1850 for (i = 0, ln = array.length; i < ln; i++) {
1854 if (comparisonFn(min, item) === 1) {
1869 * Returns the maximum value in the Array
1870 * @param {Array|NodeList} array The Array from which to select the maximum value.
1871 * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
1872 * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
1873 * @return {Mixed} maxValue The maximum value
1875 max: function(array, comparisonFn) {
1879 for (i = 0, ln = array.length; i < ln; i++) {
1883 if (comparisonFn(max, item) === -1) {
1898 * Calculates the mean of all items in the array
1899 * @param {Array} array The Array to calculate the mean value of.
1900 * @return {Number} The mean.
1902 mean: function(array) {
1903 return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
1907 * Calculates the sum of all items in the given array
1908 * @param {Array} array The Array to calculate the sum value of.
1909 * @return {Number} The sum.
1911 sum: function(array) {
1915 for (i = 0,ln = array.length; i < ln; i++) {
1927 * Convenient alias to {@link Ext.Array#each}
1931 Ext.each = Ext.Array.each;
1934 * Alias to {@link Ext.Array#merge}.
1938 Ext.Array.union = Ext.Array.merge;
1941 * Old alias to {@link Ext.Array#min}
1942 * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
1946 Ext.min = Ext.Array.min;
1949 * Old alias to {@link Ext.Array#max}
1950 * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
1954 Ext.max = Ext.Array.max;
1957 * Old alias to {@link Ext.Array#sum}
1958 * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
1962 Ext.sum = Ext.Array.sum;
1965 * Old alias to {@link Ext.Array#mean}
1966 * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
1970 Ext.mean = Ext.Array.mean;
1973 * Old alias to {@link Ext.Array#flatten}
1974 * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
1978 Ext.flatten = Ext.Array.flatten;
1981 * Old alias to {@link Ext.Array#clean Ext.Array.clean}
1982 * @deprecated 4.0.0 Use {@link Ext.Array.clean} instead
1986 Ext.clean = Ext.Array.clean;
1989 * Old alias to {@link Ext.Array#unique Ext.Array.unique}
1990 * @deprecated 4.0.0 Use {@link Ext.Array.unique} instead
1994 Ext.unique = Ext.Array.unique;
1997 * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
1998 * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
2002 Ext.pluck = Ext.Array.pluck;
2005 * Convenient alias to {@link Ext.Array#toArray Ext.Array.toArray}
2006 * @param {Iterable} the iterable object to be turned into a true Array.
2009 * @return {Array} array
2011 Ext.toArray = function() {
2012 return ExtArray.toArray.apply(ExtArray, arguments);
2017 * @class Ext.Function
2019 * A collection of useful static methods to deal with function callbacks
2026 * A very commonly used method throughout the framework. It acts as a wrapper around another method
2027 * which originally accepts 2 arguments for <code>name</code> and <code>value</code>.
2028 * The wrapped function then allows "flexible" value setting of either:
2031 * <li><code>name</code> and <code>value</code> as 2 arguments</li>
2032 * <li>one single object argument with multiple key - value pairs</li>
2037 var setValue = Ext.Function.flexSetter(function(name, value) {
2042 // Setting a single name - value
2043 setValue('name1', 'value1');
2045 // Settings multiple name - value pairs
2052 * @param {Function} setter
2053 * @returns {Function} flexSetter
2055 flexSetter: function(fn) {
2056 return function(a, b) {
2063 if (typeof a !== 'string') {
2065 if (a.hasOwnProperty(k)) {
2066 fn.call(this, k, a[k]);
2070 if (Ext.enumerables) {
2071 for (i = Ext.enumerables.length; i--;) {
2072 k = Ext.enumerables[i];
2073 if (a.hasOwnProperty(k)) {
2074 fn.call(this, k, a[k]);
2079 fn.call(this, a, b);
2087 * Create a new function from the provided <code>fn</code>, change <code>this</code> to the provided scope, optionally
2088 * overrides arguments for the call. (Defaults to the arguments passed by the caller)
2090 * @param {Function} fn The function to delegate.
2091 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2092 * <b>If omitted, defaults to the browser window.</b>
2093 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
2094 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2095 * if a number the args are inserted at the specified position
2096 * @return {Function} The new function
2098 bind: function(fn, scope, args, appendArgs) {
2103 var callArgs = args || arguments;
2105 if (appendArgs === true) {
2106 callArgs = Array.prototype.slice.call(arguments, 0);
2107 callArgs = callArgs.concat(args);
2109 else if (Ext.isNumber(appendArgs)) {
2110 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
2111 applyArgs = [appendArgs, 0].concat(args); // create method call params
2112 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
2115 return method.apply(scope || window, callArgs);
2120 * Create a new function from the provided <code>fn</code>, the arguments of which are pre-set to `args`.
2121 * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
2122 * This is especially useful when creating callbacks.
2125 var originalFunction = function(){
2126 alert(Ext.Array.from(arguments).join(' '));
2129 var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
2131 callback(); // alerts 'Hello World'
2132 callback('by Me'); // alerts 'Hello World by Me'
2134 * @param {Function} fn The original function
2135 * @param {Array} args The arguments to pass to new callback
2136 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2137 * @return {Function} The new callback function
2139 pass: function(fn, args, scope) {
2141 args = Ext.Array.from(args);
2145 return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
2150 * Create an alias to the provided method property with name <code>methodName</code> of <code>object</code>.
2151 * Note that the execution scope will still be bound to the provided <code>object</code> itself.
2153 * @param {Object/Function} object
2154 * @param {String} methodName
2155 * @return {Function} aliasFn
2157 alias: function(object, methodName) {
2159 return object[methodName].apply(object, arguments);
2164 * Creates an interceptor function. The passed function is called before the original one. If it returns false,
2165 * the original one is not called. The resulting function returns the results of the original function.
2166 * The passed function is called with the parameters of the original function. Example usage:
2168 var sayHi = function(name){
2169 alert('Hi, ' + name);
2172 sayHi('Fred'); // alerts "Hi, Fred"
2174 // create a new function that validates input without
2175 // directly modifying the original function:
2176 var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
2177 return name == 'Brian';
2180 sayHiToFriend('Fred'); // no alert
2181 sayHiToFriend('Brian'); // alerts "Hi, Brian"
2183 * @param {Function} origFn The original function.
2184 * @param {Function} newFn The function to call before the original
2185 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
2186 * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
2187 * @param {Mixed} returnValue (optional) The value to return if the passed function return false (defaults to null).
2188 * @return {Function} The new function
2190 createInterceptor: function(origFn, newFn, scope, returnValue) {
2191 var method = origFn;
2192 if (!Ext.isFunction(newFn)) {
2200 newFn.method = origFn;
2201 return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
2207 * Creates a delegate (callback) which, when called, executes after a specific delay.
2208 * @param {Function} fn The function which will be called on a delay when the returned function is called.
2209 * Optionally, a replacement (or additional) argument list may be specified.
2210 * @param {Number} delay The number of milliseconds to defer execution by whenever called.
2211 * @param {Object} scope (optional) The scope (<code>this</code> reference) used by the function at execution time.
2212 * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
2213 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2214 * if a number the args are inserted at the specified position.
2215 * @return {Function} A function which, when called, executes the original function after the specified delay.
2217 createDelayed: function(fn, delay, scope, args, appendArgs) {
2218 if (scope || args) {
2219 fn = Ext.Function.bind(fn, scope, args, appendArgs);
2223 setTimeout(function() {
2224 fn.apply(me, arguments);
2230 * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
2232 var sayHi = function(name){
2233 alert('Hi, ' + name);
2236 // executes immediately:
2239 // executes after 2 seconds:
2240 Ext.Function.defer(sayHi, 2000, this, ['Fred']);
2242 // this syntax is sometimes useful for deferring
2243 // execution of an anonymous function:
2244 Ext.Function.defer(function(){
2248 * @param {Function} fn The function to defer.
2249 * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately)
2250 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2251 * <b>If omitted, defaults to the browser window.</b>
2252 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
2253 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2254 * if a number the args are inserted at the specified position
2255 * @return {Number} The timeout id that can be used with clearTimeout
2257 defer: function(fn, millis, obj, args, appendArgs) {
2258 fn = Ext.Function.bind(fn, obj, args, appendArgs);
2260 return setTimeout(fn, millis);
2267 * Create a combined function call sequence of the original function + the passed function.
2268 * The resulting function returns the results of the original function.
2269 * The passed function is called with the parameters of the original function. Example usage:
2272 var sayHi = function(name){
2273 alert('Hi, ' + name);
2276 sayHi('Fred'); // alerts "Hi, Fred"
2278 var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
2279 alert('Bye, ' + name);
2282 sayGoodbye('Fred'); // both alerts show
2285 * @param {Function} origFn The original function.
2286 * @param {Function} newFn The function to sequence
2287 * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed.
2288 * If omitted, defaults to the scope in which the original function is called or the browser window.
2289 * @return {Function} The new function
2291 createSequence: function(origFn, newFn, scope) {
2292 if (!Ext.isFunction(newFn)) {
2297 var retval = origFn.apply(this || window, arguments);
2298 newFn.apply(scope || this || window, arguments);
2305 * <p>Creates a delegate function, optionally with a bound scope which, when called, buffers
2306 * the execution of the passed function for the configured number of milliseconds.
2307 * If called again within that period, the impending invocation will be canceled, and the
2308 * timeout period will begin again.</p>
2310 * @param {Function} fn The function to invoke on a buffered timer.
2311 * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
2313 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which
2314 * the passed function is executed. If omitted, defaults to the scope specified by the caller.
2315 * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
2316 * passed by the caller.
2317 * @return {Function} A function which invokes the passed function after buffering for the specified time.
2319 createBuffered: function(fn, buffer, scope, args) {
2325 clearInterval(timerId);
2328 timerId = setTimeout(function(){
2329 fn.apply(scope || me, args || arguments);
2336 * <p>Creates a throttled version of the passed function which, when called repeatedly and
2337 * rapidly, invokes the passed function only after a certain interval has elapsed since the
2338 * previous invocation.</p>
2340 * <p>This is useful for wrapping functions which may be called repeatedly, such as
2341 * a handler of a mouse move event when the processing is expensive.</p>
2343 * @param fn {Function} The function to execute at a regular time interval.
2344 * @param interval {Number} The interval <b>in milliseconds</b> on which the passed function is executed.
2345 * @param scope (optional) The scope (<code><b>this</b></code> reference) in which
2346 * the passed function is executed. If omitted, defaults to the scope specified by the caller.
2347 * @returns {Function} A function which invokes the passed function at the specified interval.
2349 createThrottled: function(fn, interval, scope) {
2350 var lastCallTime, elapsed, lastArgs, timer, execute = function() {
2351 fn.apply(scope || this, lastArgs);
2352 lastCallTime = new Date().getTime();
2356 elapsed = new Date().getTime() - lastCallTime;
2357 lastArgs = arguments;
2359 clearTimeout(timer);
2360 if (!lastCallTime || (elapsed >= interval)) {
2363 timer = setTimeout(execute, interval - elapsed);
2370 * Shorthand for {@link Ext.Function#defer}
2374 Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
2377 * Shorthand for {@link Ext.Function#pass}
2381 Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
2384 * Shorthand for {@link Ext.Function#bind}
2388 Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
2391 * @author Jacky Nguyen <jacky@sencha.com>
2392 * @docauthor Jacky Nguyen <jacky@sencha.com>
2395 * A collection of useful static methods to deal with objects
2402 var ExtObject = Ext.Object = {
2405 * Convert a `name` - `value` pair to an array of objects with support for nested structures; useful to construct
2406 * query strings. For example:
2408 var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
2410 // objects then equals:
2412 { name: 'hobbies', value: 'reading' },
2413 { name: 'hobbies', value: 'cooking' },
2414 { name: 'hobbies', value: 'swimming' },
2417 var objects = Ext.Object.toQueryObjects('dateOfBirth', {
2425 }, true); // Recursive
2427 // objects then equals:
2429 { name: 'dateOfBirth[day]', value: 3 },
2430 { name: 'dateOfBirth[month]', value: 8 },
2431 { name: 'dateOfBirth[year]', value: 1987 },
2432 { name: 'dateOfBirth[extra][hour]', value: 4 },
2433 { name: 'dateOfBirth[extra][minute]', value: 30 },
2436 * @param {String} name
2437 * @param {Mixed} value
2438 * @param {Boolean} recursive
2441 toQueryObjects: function(name, value, recursive) {
2442 var self = ExtObject.toQueryObjects,
2446 if (Ext.isArray(value)) {
2447 for (i = 0, ln = value.length; i < ln; i++) {
2449 objects = objects.concat(self(name + '[' + i + ']', value[i], true));
2459 else if (Ext.isObject(value)) {
2461 if (value.hasOwnProperty(i)) {
2463 objects = objects.concat(self(name + '[' + i + ']', value[i], true));
2485 * Takes an object and converts it to an encoded query string
2489 Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
2490 Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
2491 Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
2492 Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
2493 Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
2497 Ext.Object.toQueryString({
2504 hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
2505 }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
2507 // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
2508 // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
2511 * @param {Object} object The object to encode
2512 * @param {Boolean} recursive (optional) Whether or not to interpret the object in recursive format.
2513 * (PHP / Ruby on Rails servers and similar). Defaults to false
2514 * @return {String} queryString
2517 toQueryString: function(object, recursive) {
2518 var paramObjects = [],
2520 i, j, ln, paramObject, value;
2523 if (object.hasOwnProperty(i)) {
2524 paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
2528 for (j = 0, ln = paramObjects.length; j < ln; j++) {
2529 paramObject = paramObjects[j];
2530 value = paramObject.value;
2532 if (Ext.isEmpty(value)) {
2535 else if (Ext.isDate(value)) {
2536 value = Ext.Date.toString(value);
2539 params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
2542 return params.join('&');
2546 * Converts a query string back into an object.
2550 Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
2551 Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
2552 Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
2553 Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
2557 Ext.Object.fromQueryString("username=Jacky&dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
2567 hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
2570 * @param {String} queryString The query string to decode
2571 * @param {Boolean} recursive (Optional) Whether or not to recursively decode the string. This format is supported by
2572 * PHP / Ruby on Rails servers and similar. Defaults to false
2575 fromQueryString: function(queryString, recursive) {
2576 var parts = queryString.replace(/^\?/, '').split('&'),
2578 temp, components, name, value, i, ln,
2579 part, j, subLn, matchedKeys, matchedName,
2582 for (i = 0, ln = parts.length; i < ln; i++) {
2585 if (part.length > 0) {
2586 components = part.split('=');
2587 name = decodeURIComponent(components[0]);
2588 value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
2591 if (object.hasOwnProperty(name)) {
2592 if (!Ext.isArray(object[name])) {
2593 object[name] = [object[name]];
2596 object[name].push(value);
2599 object[name] = value;
2603 matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
2604 matchedName = name.match(/^([^\[]+)/);
2608 sourceClass: "Ext.Object",
2609 sourceMethod: "fromQueryString",
2610 queryString: queryString,
2611 recursive: recursive,
2612 msg: 'Malformed query string given, failed parsing name from "' + part + '"'
2616 name = matchedName[0];
2619 if (matchedKeys === null) {
2620 object[name] = value;
2624 for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
2625 key = matchedKeys[j];
2626 key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
2634 for (j = 0, subLn = keys.length; j < subLn; j++) {
2637 if (j === subLn - 1) {
2638 if (Ext.isArray(temp) && key === '') {
2646 if (temp[key] === undefined || typeof temp[key] === 'string') {
2647 nextKey = keys[j+1];
2649 temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
2663 * Iterate through an object and invoke the given callback function for each iteration. The iteration can be stop
2664 * by returning `false` in the callback function. For example:
2669 loves: ['food', 'sleeping', 'wife']
2672 Ext.Object.each(person, function(key, value, myself) {
2673 console.log(key + ":" + value);
2675 if (key === 'hairColor') {
2676 return false; // stop the iteration
2680 * @param {Object} object The object to iterate
2681 * @param {Function} fn The callback function. Passed arguments for each iteration are:
2685 - {Object} `object` The object itself
2687 * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
2690 each: function(object, fn, scope) {
2691 for (var property in object) {
2692 if (object.hasOwnProperty(property)) {
2693 if (fn.call(scope || object, property, object[property], object) === false) {
2701 * Merges any number of objects recursively without referencing them or their children.
2704 companyName: 'Ext JS',
2705 products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
2709 location: 'Palo Alto',
2715 companyName: 'Sencha Inc.',
2716 products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
2719 location: 'Redwood City'
2723 var sencha = Ext.Object.merge(extjs, newStuff);
2725 // extjs and sencha then equals to
2727 companyName: 'Sencha Inc.',
2728 products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
2732 location: 'Redwood City'
2737 * @param {Object} object,...
2738 * @return {Object} merged The object that is created as a result of merging all the objects passed in.
2741 merge: function(source, key, value) {
2742 if (typeof key === 'string') {
2743 if (value && value.constructor === Object) {
2744 if (source[key] && source[key].constructor === Object) {
2745 ExtObject.merge(source[key], value);
2748 source[key] = Ext.clone(value);
2752 source[key] = value;
2759 ln = arguments.length,
2762 for (; i < ln; i++) {
2763 object = arguments[i];
2765 for (property in object) {
2766 if (object.hasOwnProperty(property)) {
2767 ExtObject.merge(source, property, object[property]);
2776 * Returns the first matching key corresponding to the given value.
2777 * If no matching value is found, null is returned.
2784 alert(Ext.Object.getKey(sencha, 'loves')); // alerts 'food'
2786 * @param {Object} object
2787 * @param {Object} value The value to find
2790 getKey: function(object, value) {
2791 for (var property in object) {
2792 if (object.hasOwnProperty(property) && object[property] === value) {
2801 * Gets all values of the given object as an array.
2803 var values = Ext.Object.getValues({
2806 }); // ['Jacky', 'food']
2808 * @param {Object} object
2809 * @return {Array} An array of values from the object
2812 getValues: function(object) {
2816 for (property in object) {
2817 if (object.hasOwnProperty(property)) {
2818 values.push(object[property]);
2826 * Gets all keys of the given object as an array.
2828 var values = Ext.Object.getKeys({
2831 }); // ['name', 'loves']
2833 * @param {Object} object
2834 * @return {Array} An array of keys from the object
2837 getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
2841 for (property in object) {
2842 if (object.hasOwnProperty(property)) {
2843 keys.push(property);
2851 * Gets the total number of this object's own properties
2853 var size = Ext.Object.getSize({
2856 }); // size equals 2
2858 * @param {Object} object
2859 * @return {Number} size
2862 getSize: function(object) {
2866 for (property in object) {
2867 if (object.hasOwnProperty(property)) {
2878 * A convenient alias method for {@link Ext.Object#merge}
2883 Ext.merge = Ext.Object.merge;
2886 * A convenient alias method for {@link Ext.Object#toQueryString}
2890 * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString Ext.Object.toQueryString} instead
2892 Ext.urlEncode = function() {
2893 var args = Ext.Array.from(arguments),
2896 // Support for the old `pre` argument
2897 if ((typeof args[1] === 'string')) {
2898 prefix = args[1] + '&';
2902 return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
2906 * A convenient alias method for {@link Ext.Object#fromQueryString}
2910 * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString Ext.Object.fromQueryString} instead
2912 Ext.urlDecode = function() {
2913 return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
2920 * A set of useful static methods to deal with date
2921 * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
2922 * this object for convenience
2924 * The date parsing and formatting syntax contains a subset of
2925 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
2926 * supported will provide results equivalent to their PHP versions.
2928 * The following is a list of all currently supported formats:
2930 Format Description Example returned values
2931 ------ ----------------------------------------------------------------------- -----------------------
2932 d Day of the month, 2 digits with leading zeros 01 to 31
2933 D A short textual representation of the day of the week Mon to Sun
2934 j Day of the month without leading zeros 1 to 31
2935 l A full textual representation of the day of the week Sunday to Saturday
2936 N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
2937 S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
2938 w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
2939 z The day of the year (starting from 0) 0 to 364 (365 in leap years)
2940 W ISO-8601 week number of year, weeks starting on Monday 01 to 53
2941 F A full textual representation of a month, such as January or March January to December
2942 m Numeric representation of a month, with leading zeros 01 to 12
2943 M A short textual representation of a month Jan to Dec
2944 n Numeric representation of a month, without leading zeros 1 to 12
2945 t Number of days in the given month 28 to 31
2946 L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
2947 o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
2948 belongs to the previous or next year, that year is used instead)
2949 Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
2950 y A two digit representation of a year Examples: 99 or 03
2951 a Lowercase Ante meridiem and Post meridiem am or pm
2952 A Uppercase Ante meridiem and Post meridiem AM or PM
2953 g 12-hour format of an hour without leading zeros 1 to 12
2954 G 24-hour format of an hour without leading zeros 0 to 23
2955 h 12-hour format of an hour with leading zeros 01 to 12
2956 H 24-hour format of an hour with leading zeros 00 to 23
2957 i Minutes, with leading zeros 00 to 59
2958 s Seconds, with leading zeros 00 to 59
2959 u Decimal fraction of a second Examples:
2960 (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
2961 100 (i.e. 0.100s) or
2962 999 (i.e. 0.999s) or
2963 999876543210 (i.e. 0.999876543210s)
2964 O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
2965 P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
2966 T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
2967 Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
2970 1) If unspecified, the month / day defaults to the current month / day, 1991 or
2971 the time defaults to midnight, while the timezone defaults to the 1992-10 or
2972 browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
2973 and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
2974 are optional. 1995-07-18T17:21:28-02:00 or
2975 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
2976 least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
2977 of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
2978 Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
2979 date-time granularity which are supported, or see 2000-02-13T21:25:33
2980 http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
2981 U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
2982 MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
2983 \/Date(1238606590509+0800)\/
2986 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
2989 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
2991 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
2992 console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
2993 console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
2994 console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
2997 * Here are some standard date/time patterns that you might find helpful. They
2998 * are not part of the source of Ext.Date, but to use them you can simply copy this
2999 * block of code into any script that is included after Ext.Date and they will also become
3000 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
3002 Ext.Date.patterns = {
3003 ISO8601Long:"Y-m-d H:i:s",
3004 ISO8601Short:"Y-m-d",
3006 LongDate: "l, F d, Y",
3007 FullDateTime: "l, F d, Y g:i:s A",
3010 LongTime: "g:i:s A",
3011 SortableDateTime: "Y-m-d\\TH:i:s",
3012 UniversalSortableDateTime: "Y-m-d H:i:sO",
3019 var dt = new Date();
3020 console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
3022 * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
3023 * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
3028 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
3029 * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
3030 * They generate precompiled functions from format patterns instead of parsing and
3031 * processing each pattern every time a date is formatted. These functions are available
3032 * on every Date object.
3037 // create private copy of Ext's Ext.util.Format.format() method
3038 // - to remove unnecessary dependency
3039 // - to resolve namespace conflict with MS-Ajax's implementation
3040 function xf(format) {
3041 var args = Array.prototype.slice.call(arguments, 1);
3042 return format.replace(/\{(\d+)\}/g, function(m, i) {
3049 * Returns the current timestamp
3050 * @return {Date} The current timestamp
3053 now: Date.now || function() {
3061 toString: function(date) {
3062 var pad = Ext.String.leftPad;
3064 return date.getFullYear() + "-"
3065 + pad(date.getMonth() + 1, 2, '0') + "-"
3066 + pad(date.getDate(), 2, '0') + "T"
3067 + pad(date.getHours(), 2, '0') + ":"
3068 + pad(date.getMinutes(), 2, '0') + ":"
3069 + pad(date.getSeconds(), 2, '0');
3073 * Returns the number of milliseconds between two dates
3074 * @param {Date} dateA The first date
3075 * @param {Date} dateB (optional) The second date, defaults to now
3076 * @return {Number} The difference in milliseconds
3078 getElapsed: function(dateA, dateB) {
3079 return Math.abs(dateA - (dateB || new Date()));
3083 * Global flag which determines if strict date parsing should be used.
3084 * Strict date parsing will not roll-over invalid dates, which is the
3085 * default behaviour of javascript Date objects.
3086 * (see {@link #parse} for more information)
3087 * Defaults to <tt>false</tt>.
3094 formatCodeToRegex: function(character, currentGroup) {
3095 // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
3096 var p = utilDate.parseCodes[character];
3099 p = typeof p == 'function'? p() : p;
3100 utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
3103 return p ? Ext.applyIf({
3104 c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
3108 s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
3113 * <p>An object hash in which each property is a date parsing function. The property name is the
3114 * format string which that function parses.</p>
3115 * <p>This object is automatically populated with date parsing functions as
3116 * date formats are requested for Ext standard formatting strings.</p>
3117 * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
3118 * may be used as a format string to {@link #parse}.<p>
3119 * <p>Example:</p><pre><code>
3120 Ext.Date.parseFunctions['x-date-format'] = myDateParser;
3122 * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
3123 * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
3124 * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
3125 * (i.e. prevent javascript Date "rollover") (The default must be false).
3126 * Invalid date strings should return null when parsed.</div></li>
3128 * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
3129 * formatting function must be placed into the {@link #formatFunctions} property.
3130 * @property parseFunctions
3135 "MS": function(input, strict) {
3136 // note: the timezone offset is ignored since the MS Ajax server sends
3137 // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
3138 var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
3139 var r = (input || '').match(re);
3140 return r? new Date(((r[1] || '') + r[2]) * 1) : null;
3146 * <p>An object hash in which each property is a date formatting function. The property name is the
3147 * format string which corresponds to the produced formatted date string.</p>
3148 * <p>This object is automatically populated with date formatting functions as
3149 * date formats are requested for Ext standard formatting strings.</p>
3150 * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
3151 * may be used as a format string to {@link #format}. Example:</p><pre><code>
3152 Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
3154 * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
3155 * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
3157 * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
3158 * parsing function must be placed into the {@link #parseFunctions} property.
3159 * @property formatFunctions
3165 // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
3166 return '\\/Date(' + this.getTime() + ')\\/';
3173 * Date interval constant
3180 * Date interval constant
3187 * Date interval constant
3193 /** Date interval constant
3200 * Date interval constant
3207 * Date interval constant
3214 * Date interval constant
3221 * <p>An object hash containing default date values used during date parsing.</p>
3222 * <p>The following properties are available:<div class="mdetail-params"><ul>
3223 * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
3224 * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
3225 * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
3226 * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
3227 * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
3228 * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
3229 * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
3231 * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
3232 * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
3233 * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
3234 * It is the responsiblity of the developer to account for this.</b></p>
3237 // set default day value to the first day of the month
3238 Ext.Date.defaults.d = 1;
3240 // parse a February date string containing only year and month values.
3241 // setting the default day value to 1 prevents weird date rollover issues
3242 // when attempting to parse the following date string on, for example, March 31st 2009.
3243 Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
3245 * @property defaults
3252 * An array of textual day names.
3253 * Override these values for international dates.
3256 Ext.Date.dayNames = [
3276 * An array of textual month names.
3277 * Override these values for international dates.
3280 Ext.Date.monthNames = [
3305 * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
3306 * Override these values for international dates.
3309 Ext.Date.monthNumbers = {
3310 'ShortJanNameInYourLang':0,
3311 'ShortFebNameInYourLang':1,
3333 * <p>The date format string that the {@link #dateRenderer} and {@link #date} functions use.
3334 * see {@link #Date} for details.</p>
3335 * <p>This defaults to <code>m/d/Y</code>, but may be overridden in a locale file.</p>
3336 * @property defaultFormat
3340 defaultFormat : "m/d/Y",
3342 * Get the short month name for the given month number.
3343 * Override this function for international dates.
3344 * @param {Number} month A zero-based javascript month number.
3345 * @return {String} The short month name.
3348 getShortMonthName : function(month) {
3349 return utilDate.monthNames[month].substring(0, 3);
3353 * Get the short day name for the given day number.
3354 * Override this function for international dates.
3355 * @param {Number} day A zero-based javascript day number.
3356 * @return {String} The short day name.
3359 getShortDayName : function(day) {
3360 return utilDate.dayNames[day].substring(0, 3);
3364 * Get the zero-based javascript month number for the given short/full month name.
3365 * Override this function for international dates.
3366 * @param {String} name The short/full month name.
3367 * @return {Number} The zero-based javascript month number.
3370 getMonthNumber : function(name) {
3371 // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
3372 return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
3376 * Checks if the specified format contains hour information
3377 * @param {String} format The format to check
3378 * @return {Boolean} True if the format contains hour information
3382 formatContainsHourInfo : (function(){
3383 var stripEscapeRe = /(\\.)/g,
3384 hourInfoRe = /([gGhHisucUOPZ]|MS)/;
3385 return function(format){
3386 return hourInfoRe.test(format.replace(stripEscapeRe, ''));
3391 * Checks if the specified format contains information about
3392 * anything other than the time.
3393 * @param {String} format The format to check
3394 * @return {Boolean} True if the format contains information about
3395 * date/day information.
3399 formatContainsDateInfo : (function(){
3400 var stripEscapeRe = /(\\.)/g,
3401 dateInfoRe = /([djzmnYycU]|MS)/;
3403 return function(format){
3404 return dateInfoRe.test(format.replace(stripEscapeRe, ''));
3409 * The base format-code to formatting-function hashmap used by the {@link #format} method.
3410 * Formatting functions are strings (or functions which return strings) which
3411 * will return the appropriate value when evaluated in the context of the Date object
3412 * from which the {@link #format} method is called.
3413 * Add to / override these mappings for custom date formatting.
3414 * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
3417 Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
3418 console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
3424 d: "Ext.String.leftPad(this.getDate(), 2, '0')",
3425 D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
3426 j: "this.getDate()",
3427 l: "Ext.Date.dayNames[this.getDay()]",
3428 N: "(this.getDay() ? this.getDay() : 7)",
3429 S: "Ext.Date.getSuffix(this)",
3431 z: "Ext.Date.getDayOfYear(this)",
3432 W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
3433 F: "Ext.Date.monthNames[this.getMonth()]",
3434 m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
3435 M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
3436 n: "(this.getMonth() + 1)",
3437 t: "Ext.Date.getDaysInMonth(this)",
3438 L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
3439 o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
3440 Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
3441 y: "('' + this.getFullYear()).substring(2, 4)",
3442 a: "(this.getHours() < 12 ? 'am' : 'pm')",
3443 A: "(this.getHours() < 12 ? 'AM' : 'PM')",
3444 g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
3445 G: "this.getHours()",
3446 h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
3447 H: "Ext.String.leftPad(this.getHours(), 2, '0')",
3448 i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
3449 s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
3450 u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
3451 O: "Ext.Date.getGMTOffset(this)",
3452 P: "Ext.Date.getGMTOffset(this, true)",
3453 T: "Ext.Date.getTimezone(this)",
3454 Z: "(this.getTimezoneOffset() * -60)",
3456 c: function() { // ISO-8601 -- GMT format
3457 for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
3458 var e = c.charAt(i);
3459 code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
3461 return code.join(" + ");
3464 c: function() { // ISO-8601 -- UTC format
3466 "this.getUTCFullYear()", "'-'",
3467 "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
3468 "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
3470 "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
3471 "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
3472 "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
3478 U: "Math.round(this.getTime() / 1000)"
3482 * Checks if the passed Date parameters will cause a javascript Date "rollover".
3483 * @param {Number} year 4-digit year
3484 * @param {Number} month 1-based month-of-year
3485 * @param {Number} day Day of month
3486 * @param {Number} hour (optional) Hour
3487 * @param {Number} minute (optional) Minute
3488 * @param {Number} second (optional) Second
3489 * @param {Number} millisecond (optional) Millisecond
3490 * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
3493 isValid : function(y, m, d, h, i, s, ms) {
3500 // Special handling for year < 100
3501 var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
3503 return y == dt.getFullYear() &&
3504 m == dt.getMonth() + 1 &&
3505 d == dt.getDate() &&
3506 h == dt.getHours() &&
3507 i == dt.getMinutes() &&
3508 s == dt.getSeconds() &&
3509 ms == dt.getMilliseconds();
3513 * Parses the passed string using the specified date format.
3514 * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
3515 * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
3516 * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
3517 * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
3518 * Keep in mind that the input date string must precisely match the specified format string
3519 * in order for the parse operation to be successful (failed parse operations return a null value).
3520 * <p>Example:</p><pre><code>
3521 //dt = Fri May 25 2007 (current date)
3522 var dt = new Date();
3524 //dt = Thu May 25 2006 (today's month/day in 2006)
3525 dt = Ext.Date.parse("2006", "Y");
3527 //dt = Sun Jan 15 2006 (all date parts specified)
3528 dt = Ext.Date.parse("2006-01-15", "Y-m-d");
3530 //dt = Sun Jan 15 2006 15:20:01
3531 dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
3533 // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
3534 dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
3536 * @param {String} input The raw date string.
3537 * @param {String} format The expected date string format.
3538 * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
3539 (defaults to false). Invalid date strings will return null when parsed.
3540 * @return {Date} The parsed Date.
3543 parse : function(input, format, strict) {
3544 var p = utilDate.parseFunctions;
3545 if (p[format] == null) {
3546 utilDate.createParser(format);
3548 return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
3552 parseDate: function(input, format, strict){
3553 return utilDate.parse(input, format, strict);
3558 getFormatCode : function(character) {
3559 var f = utilDate.formatCodes[character];
3562 f = typeof f == 'function'? f() : f;
3563 utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
3566 // note: unknown characters are treated as literals
3567 return f || ("'" + Ext.String.escape(character) + "'");
3571 createFormat : function(format) {
3576 for (var i = 0; i < format.length; ++i) {
3577 ch = format.charAt(i);
3578 if (!special && ch == "\\") {
3580 } else if (special) {
3582 code.push("'" + Ext.String.escape(ch) + "'");
3584 code.push(utilDate.getFormatCode(ch));
3587 utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
3591 createParser : (function() {
3593 "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
3594 "def = Ext.Date.defaults,",
3595 "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
3600 "if(u != null){", // i.e. unix time is defined
3601 "v = new Date(u * 1000);", // give top priority to UNIX time
3603 // create Date object representing midnight of the current day;
3604 // this will provide us with our date defaults
3605 // (note: clearTime() handles Daylight Saving Time automatically)
3606 "dt = Ext.Date.clearTime(new Date);",
3608 // date calculations (note: these calculations create a dependency on Ext.Number.from())
3609 "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
3610 "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
3611 "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
3613 // time calculations (note: these calculations create a dependency on Ext.Number.from())
3614 "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
3615 "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
3616 "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
3617 "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
3619 "if(z >= 0 && y >= 0){",
3620 // both the year and zero-based day of year are defined and >= 0.
3621 // these 2 values alone provide sufficient info to create a full date object
3623 // create Date object representing January 1st for the given year
3624 // handle years < 100 appropriately
3625 "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
3627 // then add day of year, checking for Date "rollover" if necessary
3628 "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
3629 "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
3630 "v = null;", // invalid date, so return null
3632 // plain old Date object
3633 // handle years < 100 properly
3634 "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
3640 // favour UTC offset over GMT offset
3642 // reset to UTC, then add offset
3643 "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
3645 // reset to GMT, then add offset
3646 "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
3653 return function(format) {
3654 var regexNum = utilDate.parseRegexes.length,
3661 for (var i = 0; i < format.length; ++i) {
3662 ch = format.charAt(i);
3663 if (!special && ch == "\\") {
3665 } else if (special) {
3667 regex.push(Ext.String.escape(ch));
3669 var obj = utilDate.formatCodeToRegex(ch, currentGroup);
3670 currentGroup += obj.g;
3672 if (obj.g && obj.c) {
3678 utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
3679 utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
3687 * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
3688 * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
3689 * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
3693 c:"d = parseInt(results[{0}], 10);\n",
3694 s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
3698 c:"d = parseInt(results[{0}], 10);\n",
3699 s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
3702 for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
3706 s:"(?:" + a.join("|") +")"
3713 s:"(?:" + utilDate.dayNames.join("|") + ")"
3719 s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
3729 s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
3733 c:"z = parseInt(results[{0}], 10);\n",
3734 s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
3739 s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
3744 c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
3745 s:"(" + utilDate.monthNames.join("|") + ")"
3749 for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
3750 return Ext.applyIf({
3751 s:"(" + a.join("|") + ")"
3752 }, utilDate.formatCodeToRegex("F"));
3756 c:"m = parseInt(results[{0}], 10) - 1;\n",
3757 s:"(\\d{2})" // month number with leading zeros (01 - 12)
3761 c:"m = parseInt(results[{0}], 10) - 1;\n",
3762 s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
3767 s:"(?:\\d{2})" // no. of days in the month (28 - 31)
3775 return utilDate.formatCodeToRegex("Y");
3779 c:"y = parseInt(results[{0}], 10);\n",
3780 s:"(\\d{4})" // 4-digit year
3784 c:"var ty = parseInt(results[{0}], 10);\n"
3785 + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
3789 * In the am/pm parsing routines, we allow both upper and lower case
3790 * even though it doesn't exactly match the spec. It gives much more flexibility
3791 * in being able to specify case insensitive regexes.
3795 c:"if (/(am)/i.test(results[{0}])) {\n"
3796 + "if (!h || h == 12) { h = 0; }\n"
3797 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
3802 c:"if (/(am)/i.test(results[{0}])) {\n"
3803 + "if (!h || h == 12) { h = 0; }\n"
3804 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
3808 return utilDate.formatCodeToRegex("G");
3812 c:"h = parseInt(results[{0}], 10);\n",
3813 s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
3816 return utilDate.formatCodeToRegex("H");
3820 c:"h = parseInt(results[{0}], 10);\n",
3821 s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
3825 c:"i = parseInt(results[{0}], 10);\n",
3826 s:"(\\d{2})" // minutes with leading zeros (00 - 59)
3830 c:"s = parseInt(results[{0}], 10);\n",
3831 s:"(\\d{2})" // seconds with leading zeros (00 - 59)
3835 c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
3836 s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
3841 "o = results[{0}];",
3842 "var sn = o.substring(0,1),", // get + / - sign
3843 "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
3844 "mn = o.substring(3,5) % 60;", // get minutes
3845 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
3847 s: "([+\-]\\d{4})" // GMT offset in hrs and mins
3852 "o = results[{0}];",
3853 "var sn = o.substring(0,1),", // get + / - sign
3854 "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
3855 "mn = o.substring(4,6) % 60;", // get minutes
3856 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
3858 s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
3863 s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
3867 c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
3868 + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
3869 s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
3874 utilDate.formatCodeToRegex("Y", 1), // year
3875 utilDate.formatCodeToRegex("m", 2), // month
3876 utilDate.formatCodeToRegex("d", 3), // day
3877 utilDate.formatCodeToRegex("h", 4), // hour
3878 utilDate.formatCodeToRegex("i", 5), // minute
3879 utilDate.formatCodeToRegex("s", 6), // second
3880 {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
3881 {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
3882 "if(results[8]) {", // timezone specified
3883 "if(results[8] == 'Z'){",
3885 "}else if (results[8].indexOf(':') > -1){",
3886 utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
3888 utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
3894 for (var i = 0, l = arr.length; i < l; ++i) {
3895 calc.push(arr[i].c);
3902 arr[0].s, // year (required)
3903 "(?:", "-", arr[1].s, // month (optional)
3904 "(?:", "-", arr[2].s, // day (optional)
3906 "(?:T| )?", // time delimiter -- either a "T" or a single blank space
3907 arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
3908 "(?::", arr[5].s, ")?", // seconds (optional)
3909 "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
3910 "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
3919 c:"u = parseInt(results[{0}], 10);\n",
3920 s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
3924 //Old Ext.Date prototype methods.
3926 dateFormat: function(date, format) {
3927 return utilDate.format(date, format);
3931 * Formats a date given the supplied format string.
3932 * @param {Date} date The date to format
3933 * @param {String} format The format string
3934 * @return {String} The formatted date
3936 format: function(date, format) {
3937 if (utilDate.formatFunctions[format] == null) {
3938 utilDate.createFormat(format);
3940 var result = utilDate.formatFunctions[format].call(date);
3945 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
3947 * Note: The date string returned by the javascript Date object's toString() method varies
3948 * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
3949 * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
3950 * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
3951 * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
3952 * from the GMT offset portion of the date string.
3953 * @param {Date} date The date
3954 * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
3956 getTimezone : function(date) {
3957 // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
3959 // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
3960 // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
3961 // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
3962 // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
3963 // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
3965 // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
3966 // step 1: (?:\((.*)\) -- find timezone in parentheses
3967 // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
3968 // step 3: remove all non uppercase characters found in step 1 and 2
3969 return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
3973 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
3974 * @param {Date} date The date
3975 * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
3976 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
3978 getGMTOffset : function(date, colon) {
3979 var offset = date.getTimezoneOffset();
3980 return (offset > 0 ? "-" : "+")
3981 + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
3982 + (colon ? ":" : "")
3983 + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
3987 * Get the numeric day number of the year, adjusted for leap year.
3988 * @param {Date} date The date
3989 * @return {Number} 0 to 364 (365 in leap years).
3991 getDayOfYear: function(date) {
3993 d = Ext.Date.clone(date),
3994 m = date.getMonth(),
3997 for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
3998 num += utilDate.getDaysInMonth(d);
4000 return num + date.getDate() - 1;
4004 * Get the numeric ISO-8601 week number of the year.
4005 * (equivalent to the format specifier 'W', but without a leading zero).
4006 * @param {Date} date The date
4007 * @return {Number} 1 to 53
4010 getWeekOfYear : (function() {
4011 // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
4012 var ms1d = 864e5, // milliseconds in a day
4013 ms7d = 7 * ms1d; // milliseconds in a week
4015 return function(date) { // return a closure so constants get calculated only once
4016 var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
4017 AWN = Math.floor(DC3 / 7), // an Absolute Week Number
4018 Wyr = new Date(AWN * ms7d).getUTCFullYear();
4020 return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
4025 * Checks if the current date falls within a leap year.
4026 * @param {Date} date The date
4027 * @return {Boolean} True if the current date falls within a leap year, false otherwise.
4029 isLeapYear : function(date) {
4030 var year = date.getFullYear();
4031 return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
4035 * Get the first day of the current month, adjusted for leap year. The returned value
4036 * is the numeric day index within the week (0-6) which can be used in conjunction with
4037 * the {@link #monthNames} array to retrieve the textual day name.
4040 var dt = new Date('1/10/2007'),
4041 firstDay = Ext.Date.getFirstDayOfMonth(dt);
4042 console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
4044 * @param {Date} date The date
4045 * @return {Number} The day number (0-6).
4047 getFirstDayOfMonth : function(date) {
4048 var day = (date.getDay() - (date.getDate() - 1)) % 7;
4049 return (day < 0) ? (day + 7) : day;
4053 * Get the last day of the current month, adjusted for leap year. The returned value
4054 * is the numeric day index within the week (0-6) which can be used in conjunction with
4055 * the {@link #monthNames} array to retrieve the textual day name.
4058 var dt = new Date('1/10/2007'),
4059 lastDay = Ext.Date.getLastDayOfMonth(dt);
4060 console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
4062 * @param {Date} date The date
4063 * @return {Number} The day number (0-6).
4065 getLastDayOfMonth : function(date) {
4066 return utilDate.getLastDateOfMonth(date).getDay();
4071 * Get the date of the first day of the month in which this date resides.
4072 * @param {Date} date The date
4075 getFirstDateOfMonth : function(date) {
4076 return new Date(date.getFullYear(), date.getMonth(), 1);
4080 * Get the date of the last day of the month in which this date resides.
4081 * @param {Date} date The date
4084 getLastDateOfMonth : function(date) {
4085 return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
4089 * Get the number of days in the current month, adjusted for leap year.
4090 * @param {Date} date The date
4091 * @return {Number} The number of days in the month.
4094 getDaysInMonth: (function() {
4095 var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
4097 return function(date) { // return a closure for efficiency
4098 var m = date.getMonth();
4100 return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
4105 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
4106 * @param {Date} date The date
4107 * @return {String} 'st, 'nd', 'rd' or 'th'.
4109 getSuffix : function(date) {
4110 switch (date.getDate()) {
4127 * Creates and returns a new Date instance with the exact same date value as the called instance.
4128 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
4129 * variable will also be changed. When the intention is to create a new variable that will not
4130 * modify the original instance, you should create a clone.
4132 * Example of correctly cloning a date:
4135 var orig = new Date('10/1/2006');
4138 console.log(orig); //returns 'Thu Oct 05 2006'!
4141 var orig = new Date('10/1/2006'),
4142 copy = Ext.Date.clone(orig);
4144 console.log(orig); //returns 'Thu Oct 01 2006'
4146 * @param {Date} date The date
4147 * @return {Date} The new Date instance.
4149 clone : function(date) {
4150 return new Date(date.getTime());
4154 * Checks if the current date is affected by Daylight Saving Time (DST).
4155 * @param {Date} date The date
4156 * @return {Boolean} True if the current date is affected by DST.
4158 isDST : function(date) {
4159 // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
4160 // courtesy of @geoffrey.mcgill
4161 return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
4165 * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
4166 * automatically adjusting for Daylight Saving Time (DST) where applicable.
4167 * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
4168 * @param {Date} date The date
4169 * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
4170 * @return {Date} this or the clone.
4172 clearTime : function(date, clone) {
4174 return Ext.Date.clearTime(Ext.Date.clone(date));
4177 // get current date before clearing time
4178 var d = date.getDate();
4184 date.setMilliseconds(0);
4186 if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
4187 // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
4188 // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
4190 // increment hour until cloned date == current date
4191 for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
4194 date.setHours(c.getHours());
4201 * Provides a convenient method for performing basic date arithmetic. This method
4202 * does not modify the Date instance being called - it creates and returns
4203 * a new Date instance containing the resulting date value.
4208 var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
4209 console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
4211 // Negative values will be subtracted:
4212 var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
4213 console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
4217 * @param {Date} date The date to modify
4218 * @param {String} interval A valid date interval enum value.
4219 * @param {Number} value The amount to add to the current date.
4220 * @return {Date} The new Date instance.
4222 add : function(date, interval, value) {
4223 var d = Ext.Date.clone(date),
4225 if (!interval || value === 0) return d;
4227 switch(interval.toLowerCase()) {
4228 case Ext.Date.MILLI:
4229 d.setMilliseconds(d.getMilliseconds() + value);
4231 case Ext.Date.SECOND:
4232 d.setSeconds(d.getSeconds() + value);
4234 case Ext.Date.MINUTE:
4235 d.setMinutes(d.getMinutes() + value);
4238 d.setHours(d.getHours() + value);
4241 d.setDate(d.getDate() + value);
4243 case Ext.Date.MONTH:
4244 var day = date.getDate();
4246 day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
4249 d.setMonth(date.getMonth() + value);
4252 d.setFullYear(date.getFullYear() + value);
4259 * Checks if a date falls on or between the given start and end dates.
4260 * @param {Date} date The date to check
4261 * @param {Date} start Start date
4262 * @param {Date} end End date
4263 * @return {Boolean} true if this date falls on or between the given start and end dates.
4265 between : function(date, start, end) {
4266 var t = date.getTime();
4267 return start.getTime() <= t && t <= end.getTime();
4270 //Maintains compatibility with old static and prototype window.Date methods.
4271 compat: function() {
4272 var nativeDate = window.Date,
4274 statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
4275 proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
4278 Ext.Array.forEach(statics, function(s) {
4279 nativeDate[s] = utilDate[s];
4282 //Append to prototype
4283 Ext.Array.forEach(proto, function(s) {
4284 nativeDate.prototype[s] = function() {
4285 var args = Array.prototype.slice.call(arguments);
4287 return utilDate[s].apply(utilDate, args);
4293 var utilDate = Ext.Date;
4298 * @author Jacky Nguyen <jacky@sencha.com>
4299 * @docauthor Jacky Nguyen <jacky@sencha.com>
4302 * The root of all classes created with {@link Ext#define}
4303 * All prototype and static members of this class are inherited by any other class
4306 (function(flexSetter) {
4308 var Base = Ext.Base = function() {};
4310 $className: 'Ext.Base',
4315 * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
4316 * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
4317 * for a detailed comparison
4319 * Ext.define('My.Cat', {
4321 * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
4324 * constructor: function() {
4325 * alert(this.self.speciesName); / dependent on 'this'
4330 * clone: function() {
4331 * return new this.self();
4336 * Ext.define('My.SnowLeopard', {
4339 * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
4343 * var cat = new My.Cat(); // alerts 'Cat'
4344 * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
4346 * var clone = snowLeopard.clone();
4347 * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
4356 * Default constructor, simply returns `this`
4360 * @return {Object} this
4362 constructor: function() {
4367 * Initialize configuration for this class. a typical example:
4369 * Ext.define('My.awesome.Class', {
4370 * // The default config
4376 * constructor: function(config) {
4377 * this.initConfig(config);
4383 * var awesome = new My.awesome.Class({
4384 * name: 'Super Awesome'
4387 * alert(awesome.getName()); // 'Super Awesome'
4390 * @param {Object} config
4391 * @return {Object} mixins The mixin prototypes as key - value pairs
4394 initConfig: function(config) {
4395 if (!this.$configInited) {
4396 this.config = Ext.Object.merge({}, this.config || {}, config || {});
4398 this.applyConfig(this.config);
4400 this.$configInited = true;
4409 setConfig: function(config) {
4410 this.applyConfig(config || {});
4418 applyConfig: flexSetter(function(name, value) {
4419 var setter = 'set' + Ext.String.capitalize(name);
4421 if (typeof this[setter] === 'function') {
4422 this[setter].call(this, value);
4429 * Call the parent's overridden method. For example:
4431 * Ext.define('My.own.A', {
4432 * constructor: function(test) {
4437 * Ext.define('My.own.B', {
4438 * extend: 'My.own.A',
4440 * constructor: function(test) {
4443 * this.callParent([test + 1]);
4447 * Ext.define('My.own.C', {
4448 * extend: 'My.own.B',
4450 * constructor: function() {
4451 * alert("Going to call parent's overriden constructor...");
4453 * this.callParent(arguments);
4457 * var a = new My.own.A(1); // alerts '1'
4458 * var b = new My.own.B(1); // alerts '1', then alerts '2'
4459 * var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
4460 * // alerts '2', then alerts '3'
4463 * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
4464 * from the current method, for example: `this.callParent(arguments)`
4465 * @return {Mixed} Returns the result from the superclass' method
4468 callParent: function(args) {
4469 var method = this.callParent.caller,
4470 parentClass, methodName;
4472 if (!method.$owner) {
4473 if (!method.caller) {
4475 sourceClass: Ext.getClassName(this),
4476 sourceMethod: "callParent",
4477 msg: "Attempting to call a protected method from the public scope, which is not allowed"
4481 method = method.caller;
4484 parentClass = method.$owner.superclass;
4485 methodName = method.$name;
4487 if (!(methodName in parentClass)) {
4489 sourceClass: Ext.getClassName(this),
4490 sourceMethod: methodName,
4491 msg: "this.callParent() was called but there's no such method (" + methodName +
4492 ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"
4496 return parentClass[methodName].apply(this, args || []);
4501 * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
4502 * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
4503 * `this` points to during run-time
4505 * Ext.define('My.Cat', {
4508 * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
4511 * constructor: function() {
4512 * var statics = this.statics();
4514 * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
4515 * // equivalent to: My.Cat.speciesName
4517 * alert(this.self.speciesName); // dependent on 'this'
4519 * statics.totalCreated++;
4524 * clone: function() {
4525 * var cloned = new this.self; // dependent on 'this'
4527 * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
4534 * Ext.define('My.SnowLeopard', {
4538 * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
4541 * constructor: function() {
4542 * this.callParent();
4546 * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
4548 * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
4550 * var clone = snowLeopard.clone();
4551 * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
4552 * alert(clone.groupName); // alerts 'Cat'
4554 * alert(My.Cat.totalCreated); // alerts 3
4560 statics: function() {
4561 var method = this.statics.caller,
4568 return method.$owner;
4572 * Call the original method that was previously overridden with {@link Ext.Base#override}
4574 * Ext.define('My.Cat', {
4575 * constructor: function() {
4576 * alert("I'm a cat!");
4583 * constructor: function() {
4584 * alert("I'm going to be a cat!");
4586 * var instance = this.callOverridden();
4588 * alert("Meeeeoooowwww");
4594 * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
4595 * // alerts "I'm a cat!"
4596 * // alerts "Meeeeoooowwww"
4598 * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
4599 * @return {Mixed} Returns the result after calling the overridden method
4602 callOverridden: function(args) {
4603 var method = this.callOverridden.caller;
4605 if (!method.$owner) {
4607 sourceClass: Ext.getClassName(this),
4608 sourceMethod: "callOverridden",
4609 msg: "Attempting to call a protected method from the public scope, which is not allowed"
4613 if (!method.$previous) {
4615 sourceClass: Ext.getClassName(this),
4616 sourceMethod: "callOverridden",
4617 msg: "this.callOverridden was called in '" + method.$name +
4618 "' but this method has never been overridden"
4622 return method.$previous.apply(this, args || []);
4625 destroy: function() {}
4628 // These static properties will be copied to every newly created class with {@link Ext#define}
4629 Ext.apply(Ext.Base, {
4631 * Create a new instance of this Class.
4633 * Ext.define('My.cool.Class', {
4637 * My.cool.Class.create({
4646 create: function() {
4647 return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
4653 own: flexSetter(function(name, value) {
4654 if (typeof value === 'function') {
4655 this.ownMethod(name, value);
4658 this.prototype[name] = value;
4665 ownMethod: function(name, fn) {
4668 if (fn.$owner !== undefined && fn !== Ext.emptyFn) {
4672 return originalFn.apply(this, arguments);
4677 className = Ext.getClassName(this);
4679 fn.displayName = className + '#' + name;
4684 this.prototype[name] = fn;
4688 * Add / override static properties of this class.
4690 * Ext.define('My.cool.Class', {
4694 * My.cool.Class.addStatics({
4695 * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
4696 * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
4697 * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
4700 * @property addStatics
4703 * @param {Object} members
4706 addStatics: function(members) {
4707 for (var name in members) {
4708 if (members.hasOwnProperty(name)) {
4709 this[name] = members[name];
4717 * Add methods / properties to the prototype of this class.
4719 * Ext.define('My.awesome.Cat', {
4720 * constructor: function() {
4725 * My.awesome.Cat.implement({
4726 * meow: function() {
4727 * alert('Meowww...');
4731 * var kitty = new My.awesome.Cat;
4734 * @property implement
4737 * @param {Object} members
4740 implement: function(members) {
4741 var prototype = this.prototype,
4742 name, i, member, previous;
4743 var className = Ext.getClassName(this);
4744 for (name in members) {
4745 if (members.hasOwnProperty(name)) {
4746 member = members[name];
4748 if (typeof member === 'function') {
4749 member.$owner = this;
4750 member.$name = name;
4752 member.displayName = className + '#' + name;
4756 prototype[name] = member;
4760 if (Ext.enumerables) {
4761 var enumerables = Ext.enumerables;
4763 for (i = enumerables.length; i--;) {
4764 name = enumerables[i];
4766 if (members.hasOwnProperty(name)) {
4767 member = members[name];
4768 member.$owner = this;
4769 member.$name = name;
4770 prototype[name] = member;
4777 * Borrow another class' members to the prototype of this class.
4779 * Ext.define('Bank', {
4781 * printMoney: function() {
4786 * Ext.define('Thief', {
4790 * Thief.borrow(Bank, ['money', 'printMoney']);
4792 * var steve = new Thief();
4794 * alert(steve.money); // alerts '$$$'
4795 * steve.printMoney(); // alerts '$$$$$$$'
4800 * @param {Ext.Base} fromClass The class to borrow members from
4801 * @param {Array/String} members The names of the members to borrow
4802 * @return {Ext.Base} this
4805 borrow: function(fromClass, members) {
4806 var fromPrototype = fromClass.prototype,
4809 members = Ext.Array.from(members);
4811 for (i = 0, ln = members.length; i < ln; i++) {
4812 member = members[i];
4814 this.own(member, fromPrototype[member]);
4821 * Override prototype members of this class. Overridden methods can be invoked via
4822 * {@link Ext.Base#callOverridden}
4824 * Ext.define('My.Cat', {
4825 * constructor: function() {
4826 * alert("I'm a cat!");
4833 * constructor: function() {
4834 * alert("I'm going to be a cat!");
4836 * var instance = this.callOverridden();
4838 * alert("Meeeeoooowwww");
4844 * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
4845 * // alerts "I'm a cat!"
4846 * // alerts "Meeeeoooowwww"
4848 * @property override
4851 * @param {Object} members
4852 * @return {Ext.Base} this
4855 override: function(members) {
4856 var prototype = this.prototype,
4857 name, i, member, previous;
4859 for (name in members) {
4860 if (members.hasOwnProperty(name)) {
4861 member = members[name];
4863 if (typeof member === 'function') {
4864 if (typeof prototype[name] === 'function') {
4865 previous = prototype[name];
4866 member.$previous = previous;
4869 this.ownMethod(name, member);
4872 prototype[name] = member;
4877 if (Ext.enumerables) {
4878 var enumerables = Ext.enumerables;
4880 for (i = enumerables.length; i--;) {
4881 name = enumerables[i];
4883 if (members.hasOwnProperty(name)) {
4884 if (prototype[name] !== undefined) {
4885 previous = prototype[name];
4886 members[name].$previous = previous;
4889 this.ownMethod(name, members[name]);
4898 * Used internally by the mixins pre-processor
4901 mixin: flexSetter(function(name, cls) {
4902 var mixin = cls.prototype,
4903 my = this.prototype,
4907 if (mixin.hasOwnProperty(i)) {
4908 if (my[i] === undefined) {
4909 if (typeof mixin[i] === 'function') {
4912 if (fn.$owner === undefined) {
4913 this.ownMethod(i, fn);
4923 else if (i === 'config' && my.config && mixin.config) {
4924 Ext.Object.merge(my.config, mixin.config);
4929 if (my.mixins === undefined) {
4933 my.mixins[name] = mixin;
4937 * Get the current class' name in string format.
4939 * Ext.define('My.cool.Class', {
4940 * constructor: function() {
4941 * alert(this.self.getName()); // alerts 'My.cool.Class'
4945 * My.cool.Class.getName(); // 'My.cool.Class'
4947 * @return {String} className
4950 getName: function() {
4951 return Ext.getClassName(this);
4955 * Create aliases for existing prototype methods. Example:
4957 * Ext.define('My.cool.Class', {
4958 * method1: function() { ... },
4959 * method2: function() { ... }
4962 * var test = new My.cool.Class();
4964 * My.cool.Class.createAlias({
4965 * method3: 'method1',
4966 * method4: 'method2'
4969 * test.method3(); // test.method1()
4971 * My.cool.Class.createAlias('method5', 'method3');
4973 * test.method5(); // test.method3() -> test.method1()
4975 * @property createAlias
4978 * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
4979 * {@link Ext.Function#flexSetter flexSetter}
4980 * @param {String/Object} origin The original method name
4983 createAlias: flexSetter(function(alias, origin) {
4984 this.prototype[alias] = this.prototype[origin];
4988 })(Ext.Function.flexSetter);
4991 * @author Jacky Nguyen <jacky@sencha.com>
4992 * @docauthor Jacky Nguyen <jacky@sencha.com>
4995 * Handles class creation throughout the whole framework. Note that most of the time {@link Ext#define Ext.define} should
4996 * be used instead, since it's a higher level wrapper that aliases to {@link Ext.ClassManager#create}
4997 * to enable namespacing and dynamic dependency resolution.
5001 * Ext.define(className, properties);
5003 * in which `properties` is an object represent a collection of properties that apply to the class. See
5004 * {@link Ext.ClassManager#create} for more detailed instructions.
5006 * Ext.define('Person', {
5009 * constructor: function(name) {
5017 * eat: function(foodType) {
5018 * alert("I'm eating: " + foodType);
5024 * var aaron = new Person("Aaron");
5025 * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
5027 * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
5028 * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
5032 * Ext.define('Developer', {
5035 * constructor: function(name, isGeek) {
5036 * this.isGeek = isGeek;
5038 * // Apply a method from the parent class' prototype
5039 * this.callParent([name]);
5045 * code: function(language) {
5046 * alert("I'm coding in: " + language);
5054 * var jacky = new Developer("Jacky", true);
5055 * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
5056 * // alert("I'm eating: Bugs");
5058 * See {@link Ext.Base#callParent} for more details on calling superclass' methods
5062 * Ext.define('CanPlayGuitar', {
5063 * playGuitar: function() {
5064 * alert("F#...G...D...A");
5068 * Ext.define('CanComposeSongs', {
5069 * composeSongs: function() { ... }
5072 * Ext.define('CanSing', {
5073 * sing: function() {
5074 * alert("I'm on the highway to hell...")
5078 * Ext.define('Musician', {
5082 * canPlayGuitar: 'CanPlayGuitar',
5083 * canComposeSongs: 'CanComposeSongs',
5084 * canSing: 'CanSing'
5088 * Ext.define('CoolPerson', {
5092 * canPlayGuitar: 'CanPlayGuitar',
5093 * canSing: 'CanSing'
5096 * sing: function() {
5097 * alert("Ahem....");
5099 * this.mixins.canSing.sing.call(this);
5101 * alert("[Playing guitar at the same time...]");
5103 * this.playGuitar();
5107 * var me = new CoolPerson("Jacky");
5109 * me.sing(); // alert("Ahem...");
5110 * // alert("I'm on the highway to hell...");
5111 * // alert("[Playing guitar at the same time...]");
5112 * // alert("F#...G...D...A");
5116 * Ext.define('SmartPhone', {
5118 * hasTouchScreen: false,
5119 * operatingSystem: 'Other',
5123 * isExpensive: false,
5125 * constructor: function(config) {
5126 * this.initConfig(config);
5131 * applyPrice: function(price) {
5132 * this.isExpensive = (price > 500);
5137 * applyOperatingSystem: function(operatingSystem) {
5138 * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
5142 * return operatingSystem;
5146 * var iPhone = new SmartPhone({
5147 * hasTouchScreen: true,
5148 * operatingSystem: 'iOS'
5151 * iPhone.getPrice(); // 500;
5152 * iPhone.getOperatingSystem(); // 'iOS'
5153 * iPhone.getHasTouchScreen(); // true;
5154 * iPhone.hasTouchScreen(); // true
5156 * iPhone.isExpensive; // false;
5157 * iPhone.setPrice(600);
5158 * iPhone.getPrice(); // 600
5159 * iPhone.isExpensive; // true;
5161 * iPhone.setOperatingSystem('AlienOS');
5162 * iPhone.getOperatingSystem(); // 'Other'
5166 * Ext.define('Computer', {
5168 * factory: function(brand) {
5169 * // 'this' in static methods refer to the class itself
5170 * return new this(brand);
5174 * constructor: function() { ... }
5177 * var dellComputer = Computer.factory('Dell');
5179 * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
5180 * static properties within class methods
5187 baseStaticProperties = [],
5190 for (baseStaticProperty in Base) {
5191 if (Base.hasOwnProperty(baseStaticProperty)) {
5192 baseStaticProperties.push(baseStaticProperty);
5198 * @param {Object} classData An object represent the properties of this class
5199 * @param {Function} createdFn Optional, the callback function to be executed when this class is fully created.
5200 * Note that the creation process can be asynchronous depending on the pre-processors used.
5201 * @return {Ext.Base} The newly created class
5203 Ext.Class = Class = function(newClass, classData, onClassCreated) {
5204 if (typeof newClass !== 'function') {
5205 onClassCreated = classData;
5206 classData = newClass;
5207 newClass = function() {
5208 return this.constructor.apply(this, arguments);
5216 var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
5217 registeredPreprocessors = Class.getPreprocessors(),
5220 preprocessor, preprocessors, staticPropertyName, process, i, j, ln;
5222 for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
5223 staticPropertyName = baseStaticProperties[i];
5224 newClass[staticPropertyName] = Base[staticPropertyName];
5227 delete classData.preprocessors;
5229 for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
5230 preprocessor = preprocessorStack[j];
5232 if (typeof preprocessor === 'string') {
5233 preprocessor = registeredPreprocessors[preprocessor];
5235 if (!preprocessor.always) {
5236 if (classData.hasOwnProperty(preprocessor.name)) {
5237 preprocessors.push(preprocessor.fn);
5241 preprocessors.push(preprocessor.fn);
5245 preprocessors.push(preprocessor);
5249 classData.onClassCreated = onClassCreated;
5251 classData.onBeforeClassCreated = function(cls, data) {
5252 onClassCreated = data.onClassCreated;
5254 delete data.onBeforeClassCreated;
5255 delete data.onClassCreated;
5257 cls.implement(data);
5259 if (onClassCreated) {
5260 onClassCreated.call(cls, cls);
5264 process = function(cls, data) {
5265 preprocessor = preprocessors[index++];
5267 if (!preprocessor) {
5268 data.onBeforeClassCreated.apply(this, arguments);
5272 if (preprocessor.call(this, cls, data, process) !== false) {
5273 process.apply(this, arguments);
5277 process.call(Class, newClass, classData);
5288 * Register a new pre-processor to be used during the class creation process
5290 * @member Ext.Class registerPreprocessor
5291 * @param {String} name The pre-processor's name
5292 * @param {Function} fn The callback function to be executed. Typical format:
5294 function(cls, data, fn) {
5297 // Execute this when the processing is finished.
5298 // Asynchronous processing is perfectly ok
5300 fn.call(this, cls, data);
5304 * Passed arguments for this function are:
5306 * - `{Function} cls`: The created class
5307 * - `{Object} data`: The set of properties passed in {@link Ext.Class} constructor
5308 * - `{Function} fn`: The callback function that <b>must</b> to be executed when this pre-processor finishes,
5309 * regardless of whether the processing is synchronous or aynchronous
5311 * @return {Ext.Class} this
5314 registerPreprocessor: function(name, fn, always) {
5315 this.preprocessors[name] = {
5317 always: always || false,
5325 * Retrieve a pre-processor callback function by its name, which has been registered before
5327 * @param {String} name
5328 * @return {Function} preprocessor
5330 getPreprocessor: function(name) {
5331 return this.preprocessors[name];
5334 getPreprocessors: function() {
5335 return this.preprocessors;
5339 * Retrieve the array stack of default pre-processors
5341 * @return {Function} defaultPreprocessors
5343 getDefaultPreprocessors: function() {
5344 return this.defaultPreprocessors || [];
5348 * Set the default array stack of default pre-processors
5350 * @param {Array} preprocessors
5351 * @return {Ext.Class} this
5353 setDefaultPreprocessors: function(preprocessors) {
5354 this.defaultPreprocessors = Ext.Array.from(preprocessors);
5360 * Insert this pre-processor at a specific position in the stack, optionally relative to
5361 * any existing pre-processor. For example:
5363 Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
5367 fn.call(this, cls, data);
5369 }).insertDefaultPreprocessor('debug', 'last');
5371 * @param {String} name The pre-processor name. Note that it needs to be registered with
5372 * {@link Ext#registerPreprocessor registerPreprocessor} before this
5373 * @param {String} offset The insertion position. Four possible values are:
5374 * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
5375 * @param {String} relativeName
5376 * @return {Ext.Class} this
5379 setDefaultPreprocessorPosition: function(name, offset, relativeName) {
5380 var defaultPreprocessors = this.defaultPreprocessors,
5383 if (typeof offset === 'string') {
5384 if (offset === 'first') {
5385 defaultPreprocessors.unshift(name);
5389 else if (offset === 'last') {
5390 defaultPreprocessors.push(name);
5395 offset = (offset === 'after') ? 1 : -1;
5398 index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
5401 defaultPreprocessors.splice(Math.max(0, index + offset), 0, name);
5408 Class.registerPreprocessor('extend', function(cls, data) {
5409 var extend = data.extend,
5411 basePrototype = base.prototype,
5412 prototype = function() {},
5413 parent, i, k, ln, staticName, parentStatics,
5414 parentPrototype, clsPrototype;
5416 if (extend && extend !== Object) {
5423 parentPrototype = parent.prototype;
5425 prototype.prototype = parentPrototype;
5426 clsPrototype = cls.prototype = new prototype();
5428 if (!('$class' in parent)) {
5429 for (i in basePrototype) {
5430 if (!parentPrototype[i]) {
5431 parentPrototype[i] = basePrototype[i];
5436 clsPrototype.self = cls;
5438 cls.superclass = clsPrototype.superclass = parentPrototype;
5442 // Statics inheritance
5443 parentStatics = parentPrototype.$inheritableStatics;
5445 if (parentStatics) {
5446 for (k = 0, ln = parentStatics.length; k < ln; k++) {
5447 staticName = parentStatics[k];
5449 if (!cls.hasOwnProperty(staticName)) {
5450 cls[staticName] = parent[staticName];
5455 // Merge the parent class' config object without referencing it
5456 if (parentPrototype.config) {
5457 clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
5460 clsPrototype.config = {};
5463 if (clsPrototype.$onExtended) {
5464 clsPrototype.$onExtended.call(cls, cls, data);
5467 if (data.onClassExtended) {
5468 clsPrototype.$onExtended = data.onClassExtended;
5469 delete data.onClassExtended;
5474 Class.registerPreprocessor('statics', function(cls, data) {
5475 var statics = data.statics,
5478 for (name in statics) {
5479 if (statics.hasOwnProperty(name)) {
5480 cls[name] = statics[name];
5484 delete data.statics;
5487 Class.registerPreprocessor('inheritableStatics', function(cls, data) {
5488 var statics = data.inheritableStatics,
5490 prototype = cls.prototype,
5493 inheritableStatics = prototype.$inheritableStatics;
5495 if (!inheritableStatics) {
5496 inheritableStatics = prototype.$inheritableStatics = [];
5499 for (name in statics) {
5500 if (statics.hasOwnProperty(name)) {
5501 cls[name] = statics[name];
5502 inheritableStatics.push(name);
5506 delete data.inheritableStatics;
5509 Class.registerPreprocessor('mixins', function(cls, data) {
5510 cls.mixin(data.mixins);
5515 Class.registerPreprocessor('config', function(cls, data) {
5516 var prototype = cls.prototype;
5518 Ext.Object.each(data.config, function(name) {
5519 var cName = name.charAt(0).toUpperCase() + name.substr(1),
5521 apply = 'apply' + cName,
5522 setter = 'set' + cName,
5523 getter = 'get' + cName;
5525 if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
5526 data[apply] = function(val) {
5531 if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
5532 data[setter] = function(val) {
5533 var ret = this[apply].call(this, val, this[pName]);
5535 if (ret !== undefined) {
5543 if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
5544 data[getter] = function() {
5550 Ext.Object.merge(prototype.config, data.config);
5554 Class.setDefaultPreprocessors(['extend', 'statics', 'inheritableStatics', 'mixins', 'config']);
5556 // Backwards compatible
5557 Ext.extend = function(subclass, superclass, members) {
5558 if (arguments.length === 2 && Ext.isObject(superclass)) {
5559 members = superclass;
5560 superclass = subclass;
5567 Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
5570 members.extend = superclass;
5571 members.preprocessors = ['extend', 'mixins', 'config', 'statics'];
5574 cls = new Class(subclass, members);
5577 cls = new Class(members);
5580 cls.prototype.override = function(o) {
5582 if (o.hasOwnProperty(m)) {
5594 * @author Jacky Nguyen <jacky@sencha.com>
5595 * @docauthor Jacky Nguyen <jacky@sencha.com>
5596 * @class Ext.ClassManager
5598 Ext.ClassManager manages all classes and handles mapping from string class name to
5599 actual class objects throughout the whole framework. It is not generally accessed directly, rather through
5600 these convenient shorthands:
5602 - {@link Ext#define Ext.define}
5603 - {@link Ext#create Ext.create}
5604 - {@link Ext#widget Ext.widget}
5605 - {@link Ext#getClass Ext.getClass}
5606 - {@link Ext#getClassName Ext.getClassName}
5611 (function(Class, alias) {
5613 var slice = Array.prototype.slice;
5615 var Manager = Ext.ClassManager = {
5620 * All classes which were defined through the ClassManager. Keys are the
5621 * name of the classes and the values are references to the classes.
5634 namespaceRewrites: [{
5643 alternateToName: {},
5649 enableNamespaceParseCache: true,
5652 namespaceParseCache: {},
5658 instantiationCounts: {},
5661 * Checks if a class has already been created.
5663 * @param {String} className
5664 * @return {Boolean} exist
5666 isCreated: function(className) {
5667 var i, ln, part, root, parts;
5669 if (typeof className !== 'string' || className.length < 1) {
5671 sourceClass: "Ext.ClassManager",
5672 sourceMethod: "exist",
5673 msg: "Invalid classname, must be a string and must not be empty"
5677 if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
5682 parts = this.parseNamespace(className);
5684 for (i = 0, ln = parts.length; i < ln; i++) {
5687 if (typeof part !== 'string') {
5690 if (!root || !root[part]) {
5698 Ext.Loader.historyPush(className);
5700 this.existCache[className] = true;
5706 * Supports namespace rewriting
5709 parseNamespace: function(namespace) {
5710 if (typeof namespace !== 'string') {
5712 sourceClass: "Ext.ClassManager",
5713 sourceMethod: "parseNamespace",
5714 msg: "Invalid namespace, must be a string"
5718 var cache = this.namespaceParseCache;
5720 if (this.enableNamespaceParseCache) {
5721 if (cache.hasOwnProperty(namespace)) {
5722 return cache[namespace];
5727 rewrites = this.namespaceRewrites,
5728 rewrite, from, to, i, ln, root = Ext.global;
5730 for (i = 0, ln = rewrites.length; i < ln; i++) {
5731 rewrite = rewrites[i];
5732 from = rewrite.from;
5735 if (namespace === from || namespace.substring(0, from.length) === from) {
5736 namespace = namespace.substring(from.length);
5738 if (typeof to !== 'string') {
5741 parts = parts.concat(to.split('.'));
5750 parts = parts.concat(namespace.split('.'));
5752 if (this.enableNamespaceParseCache) {
5753 cache[namespace] = parts;
5760 * Creates a namespace and assign the `value` to the created object
5762 Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
5764 alert(MyCompany.pkg.Example === someObject); // alerts true
5766 * @param {String} name
5767 * @param {Mixed} value
5770 setNamespace: function(name, value) {
5771 var root = Ext.global,
5772 parts = this.parseNamespace(name),
5776 for (i = 0, ln = parts.length; i < ln; i++) {
5779 if (typeof part !== 'string') {
5796 * The new Ext.ns, supports namespace rewriting
5799 createNamespaces: function() {
5800 var root = Ext.global,
5801 parts, part, i, j, ln, subLn;
5803 for (i = 0, ln = arguments.length; i < ln; i++) {
5804 parts = this.parseNamespace(arguments[i]);
5806 for (j = 0, subLn = parts.length; j < subLn; j++) {
5809 if (typeof part !== 'string') {
5825 * Sets a name reference to a class.
5827 * @param {String} name
5828 * @param {Object} value
5829 * @return {Ext.ClassManager} this
5831 set: function(name, value) {
5832 var targetName = this.getName(value);
5834 this.classes[name] = this.setNamespace(name, value);
5836 if (targetName && targetName !== name) {
5837 this.maps.alternateToName[name] = targetName;
5844 * Retrieve a class by its name.
5846 * @param {String} name
5847 * @return {Class} class
5849 get: function(name) {
5850 if (this.classes.hasOwnProperty(name)) {
5851 return this.classes[name];
5854 var root = Ext.global,
5855 parts = this.parseNamespace(name),
5858 for (i = 0, ln = parts.length; i < ln; i++) {
5861 if (typeof part !== 'string') {
5864 if (!root || !root[part]) {
5876 * Register the alias for a class.
5878 * @param {Class/String} cls a reference to a class or a className
5879 * @param {String} alias Alias to use when referring to this class
5881 setAlias: function(cls, alias) {
5882 var aliasToNameMap = this.maps.aliasToName,
5883 nameToAliasesMap = this.maps.nameToAliases,
5886 if (typeof cls === 'string') {
5889 className = this.getName(cls);
5892 if (alias && aliasToNameMap[alias] !== className) {
5893 if (aliasToNameMap.hasOwnProperty(alias) && Ext.isDefined(Ext.global.console)) {
5894 Ext.global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
5895 "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
5898 aliasToNameMap[alias] = className;
5901 if (!nameToAliasesMap[className]) {
5902 nameToAliasesMap[className] = [];
5906 Ext.Array.include(nameToAliasesMap[className], alias);
5913 * Get a reference to the class by its alias.
5915 * @param {String} alias
5916 * @return {Class} class
5918 getByAlias: function(alias) {
5919 return this.get(this.getNameByAlias(alias));
5923 * Get the name of a class by its alias.
5925 * @param {String} alias
5926 * @return {String} className
5928 getNameByAlias: function(alias) {
5929 return this.maps.aliasToName[alias] || '';
5933 * Get the name of a class by its alternate name.
5935 * @param {String} alternate
5936 * @return {String} className
5938 getNameByAlternate: function(alternate) {
5939 return this.maps.alternateToName[alternate] || '';
5943 * Get the aliases of a class by the class name
5945 * @param {String} name
5946 * @return {Array} aliases
5948 getAliasesByName: function(name) {
5949 return this.maps.nameToAliases[name] || [];
5953 * Get the name of the class by its reference or its instance;
5954 * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
5956 Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
5958 * @param {Class/Object} object
5959 * @return {String} className
5962 getName: function(object) {
5963 return object && object.$className || '';
5967 * Get the class of the provided object; returns null if it's not an instance
5968 * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
5970 var component = new Ext.Component();
5972 Ext.ClassManager.getClass(component); // returns Ext.Component
5974 * @param {Object} object
5975 * @return {Class} class
5978 getClass: function(object) {
5979 return object && object.self || null;
5983 * Defines a class. This is usually invoked via the alias {@link Ext#define Ext.define}
5985 Ext.ClassManager.create('My.awesome.Class', {
5986 someProperty: 'something',
5987 someMethod: function() { ... }
5992 alert(this === My.awesome.Class); // alerts true
5994 var myInstance = new this();
5997 * @param {String} className The class name to create in string dot-namespaced format, for example:
5998 * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
5999 * It is highly recommended to follow this simple convention:
6001 - The root and the class name are 'CamelCased'
6002 - Everything else is lower-cased
6004 * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
6005 * strings, except those in the reserved listed below:
6013 - `alternateClassName`
6015 * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
6016 * (`this`) will be the newly created class itself.
6017 * @return {Ext.Base}
6020 create: function(className, data, createdFn) {
6023 if (typeof className !== 'string') {
6026 sourceMethod: "define",
6027 msg: "Invalid class name '" + className + "' specified, must be a non-empty string"
6031 data.$className = className;
6033 return new Class(data, function() {
6034 var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
6035 registeredPostprocessors = manager.postprocessors,
6037 postprocessors = [],
6038 postprocessor, postprocessors, process, i, ln;
6040 delete data.postprocessors;
6042 for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
6043 postprocessor = postprocessorStack[i];
6045 if (typeof postprocessor === 'string') {
6046 postprocessor = registeredPostprocessors[postprocessor];
6048 if (!postprocessor.always) {
6049 if (data[postprocessor.name] !== undefined) {
6050 postprocessors.push(postprocessor.fn);
6054 postprocessors.push(postprocessor.fn);
6058 postprocessors.push(postprocessor);
6062 process = function(clsName, cls, clsData) {
6063 postprocessor = postprocessors[index++];
6065 if (!postprocessor) {
6066 manager.set(className, cls);
6068 Ext.Loader.historyPush(className);
6071 createdFn.call(cls, cls);
6077 if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
6078 process.apply(this, arguments);
6082 process.call(manager, className, this, data);
6087 * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
6088 * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
6089 * attempt to load the class via synchronous loading.
6091 var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
6093 * @param {String} alias
6094 * @param {Mixed} args,... Additional arguments after the alias will be passed to the
6095 * class constructor.
6096 * @return {Object} instance
6099 instantiateByAlias: function() {
6100 var alias = arguments[0],
6101 args = slice.call(arguments),
6102 className = this.getNameByAlias(alias);
6105 className = this.maps.aliasToName[alias];
6110 sourceMethod: "createByAlias",
6111 msg: "Cannot create an instance of unrecognized alias: " + alias
6115 if (Ext.global.console) {
6116 Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
6117 "Ext.require('" + alias + "') above Ext.onReady");
6120 Ext.syncRequire(className);
6123 args[0] = className;
6125 return this.instantiate.apply(this, args);
6129 * Instantiate a class by either full name, alias or alternate name; usually invoked by the convenient
6130 * shorthand {@link Ext#create Ext.create}
6132 * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
6133 * attempt to load the class via synchronous loading.
6135 * For example, all these three lines return the same result:
6138 var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
6141 var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
6144 var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
6146 * @param {String} name
6147 * @param {Mixed} args,... Additional arguments after the name will be passed to the class' constructor.
6148 * @return {Object} instance
6151 instantiate: function() {
6152 var name = arguments[0],
6153 args = slice.call(arguments, 1),
6157 if (typeof name !== 'function') {
6158 if ((typeof name !== 'string' || name.length < 1)) {
6161 sourceMethod: "create",
6162 msg: "Invalid class name or alias '" + name + "' specified, must be a non-empty string"
6166 cls = this.get(name);
6172 // No record of this class name, it's possibly an alias, so look it up
6174 possibleName = this.getNameByAlias(name);
6177 name = possibleName;
6179 cls = this.get(name);
6183 // Still no record of this class name, it's possibly an alternate name, so look it up
6185 possibleName = this.getNameByAlternate(name);
6188 name = possibleName;
6190 cls = this.get(name);
6194 // Still not existing at this point, try to load it via synchronous mode as the last resort
6196 if (Ext.global.console) {
6197 Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
6198 "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
6201 Ext.syncRequire(name);
6203 cls = this.get(name);
6209 sourceMethod: "create",
6210 msg: "Cannot create an instance of unrecognized class name / alias: " + alias
6214 if (typeof cls !== 'function') {
6217 sourceMethod: "create",
6218 msg: "'" + name + "' is a singleton and cannot be instantiated"
6222 if (!this.instantiationCounts[name]) {
6223 this.instantiationCounts[name] = 0;
6226 this.instantiationCounts[name]++;
6228 return this.getInstantiator(args.length)(cls, args);
6236 dynInstantiate: function(name, args) {
6237 args = Ext.Array.from(args, true);
6240 return this.instantiate.apply(this, args);
6247 getInstantiator: function(length) {
6248 if (!this.instantiators[length]) {
6252 for (i = 0; i < length; i++) {
6253 args.push('a['+i+']');
6256 this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
6259 return this.instantiators[length];
6270 defaultPostprocessors: [],
6273 * Register a post-processor function.
6275 * @param {String} name
6276 * @param {Function} postprocessor
6278 registerPostprocessor: function(name, fn, always) {
6279 this.postprocessors[name] = {
6281 always: always || false,
6289 * Set the default post processors array stack which are applied to every class.
6291 * @param {String/Array} The name of a registered post processor or an array of registered names.
6292 * @return {Ext.ClassManager} this
6294 setDefaultPostprocessors: function(postprocessors) {
6295 this.defaultPostprocessors = Ext.Array.from(postprocessors);
6301 * Insert this post-processor at a specific position in the stack, optionally relative to
6302 * any existing post-processor
6304 * @param {String} name The post-processor name. Note that it needs to be registered with
6305 * {@link Ext.ClassManager#registerPostprocessor} before this
6306 * @param {String} offset The insertion position. Four possible values are:
6307 * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
6308 * @param {String} relativeName
6309 * @return {Ext.ClassManager} this
6311 setDefaultPostprocessorPosition: function(name, offset, relativeName) {
6312 var defaultPostprocessors = this.defaultPostprocessors,
6315 if (typeof offset === 'string') {
6316 if (offset === 'first') {
6317 defaultPostprocessors.unshift(name);
6321 else if (offset === 'last') {
6322 defaultPostprocessors.push(name);
6327 offset = (offset === 'after') ? 1 : -1;
6330 index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
6333 defaultPostprocessors.splice(Math.max(0, index + offset), 0, name);
6340 * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
6341 * or class names. Expressions support wildcards:
6343 // returns ['Ext.window.Window']
6344 var window = Ext.ClassManager.getNamesByExpression('widget.window');
6346 // returns ['widget.panel', 'widget.window', ...]
6347 var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
6349 // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
6350 var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
6352 * @param {String} expression
6353 * @return {Array} classNames
6356 getNamesByExpression: function(expression) {
6357 var nameToAliasesMap = this.maps.nameToAliases,
6359 name, alias, aliases, possibleName, regex, i, ln;
6361 if (typeof expression !== 'string' || expression.length < 1) {
6363 sourceClass: "Ext.ClassManager",
6364 sourceMethod: "getNamesByExpression",
6365 msg: "Expression " + expression + " is invalid, must be a non-empty string"
6369 if (expression.indexOf('*') !== -1) {
6370 expression = expression.replace(/\*/g, '(.*?)');
6371 regex = new RegExp('^' + expression + '$');
6373 for (name in nameToAliasesMap) {
6374 if (nameToAliasesMap.hasOwnProperty(name)) {
6375 aliases = nameToAliasesMap[name];
6377 if (name.search(regex) !== -1) {
6381 for (i = 0, ln = aliases.length; i < ln; i++) {
6384 if (alias.search(regex) !== -1) {
6394 possibleName = this.getNameByAlias(expression);
6397 names.push(possibleName);
6399 possibleName = this.getNameByAlternate(expression);
6402 names.push(possibleName);
6404 names.push(expression);
6413 Manager.registerPostprocessor('alias', function(name, cls, data) {
6414 var aliases = data.alias,
6415 widgetPrefix = 'widget.',
6418 if (!(aliases instanceof Array)) {
6419 aliases = [aliases];
6422 for (i = 0, ln = aliases.length; i < ln; i++) {
6425 if (typeof alias !== 'string') {
6428 sourceMethod: "define",
6429 msg: "Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"
6433 this.setAlias(cls, alias);
6436 // This is ugly, will change to make use of parseNamespace for alias later on
6437 for (i = 0, ln = aliases.length; i < ln; i++) {
6440 if (alias.substring(0, widgetPrefix.length) === widgetPrefix) {
6441 // Only the first alias with 'widget.' prefix will be used for xtype
6442 cls.xtype = cls.$xtype = alias.substring(widgetPrefix.length);
6448 Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
6449 fn.call(this, name, new cls(), data);
6453 Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
6454 var alternates = data.alternateClassName,
6457 if (!(alternates instanceof Array)) {
6458 alternates = [alternates];
6461 for (i = 0, ln = alternates.length; i < ln; i++) {
6462 alternate = alternates[i];
6464 if (typeof alternate !== 'string') {
6467 sourceMethod: "define",
6468 msg: "Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"
6472 this.set(alternate, cls);
6476 Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
6480 * Convenient shorthand, see {@link Ext.ClassManager#instantiate}
6484 create: alias(Manager, 'instantiate'),
6488 * API to be stablized
6490 * @param {Mixed} item
6491 * @param {String} namespace
6493 factory: function(item, namespace) {
6494 if (item instanceof Array) {
6497 for (i = 0, ln = item.length; i < ln; i++) {
6498 item[i] = Ext.factory(item[i], namespace);
6504 var isString = (typeof item === 'string');
6506 if (isString || (item instanceof Object && item.constructor === Object)) {
6507 var name, config = {};
6513 name = item.className;
6515 delete config.className;
6518 if (namespace !== undefined && name.indexOf(namespace) === -1) {
6519 name = namespace + '.' + Ext.String.capitalize(name);
6522 return Ext.create(name, config);
6525 if (typeof item === 'function') {
6526 return Ext.create(item);
6533 * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
6535 var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
6536 var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
6542 widget: function(name) {
6543 var args = slice.call(arguments);
6544 args[0] = 'widget.' + name;
6546 return Manager.instantiateByAlias.apply(Manager, args);
6550 * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
6552 * @method createByAlias
6554 createByAlias: alias(Manager, 'instantiateByAlias'),
6557 * Convenient shorthand for {@link Ext.ClassManager#create}, see detailed {@link Ext.Class explanation}
6561 define: alias(Manager, 'create'),
6564 * Convenient shorthand, see {@link Ext.ClassManager#getName}
6566 * @method getClassName
6568 getClassName: alias(Manager, 'getName'),
6572 * @param {Mixed} object
6574 getDisplayName: function(object) {
6575 if (object.displayName) {
6576 return object.displayName;
6579 if (object.$name && object.$class) {
6580 return Ext.getClassName(object.$class) + '#' + object.$name;
6583 if (object.$className) {
6584 return object.$className;
6591 * Convenient shorthand, see {@link Ext.ClassManager#getClass}
6593 * @method getClassName
6595 getClass: alias(Manager, 'getClass'),
6598 * Creates namespaces to be used for scoping variables and classes so that they are not global.
6599 * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
6601 Ext.namespace('Company', 'Company.data');
6603 // equivalent and preferable to the above syntax
6604 Ext.namespace('Company.data');
6606 Company.Widget = function() { ... };
6608 Company.data.CustomStore = function(config) { ... };
6610 * @param {String} namespace1
6611 * @param {String} namespace2
6612 * @param {String} etc
6613 * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
6619 namespace: alias(Manager, 'createNamespaces')
6622 Ext.createWidget = Ext.widget;
6625 * Convenient alias for {@link Ext#namespace Ext.namespace}
6629 Ext.ns = Ext.namespace;
6631 Class.registerPreprocessor('className', function(cls, data) {
6632 if (data.$className) {
6633 cls.$className = data.$className;
6634 cls.displayName = cls.$className;
6638 Class.setDefaultPreprocessorPosition('className', 'first');
6640 })(Ext.Class, Ext.Function.alias);
6643 * @author Jacky Nguyen <jacky@sencha.com>
6644 * @docauthor Jacky Nguyen <jacky@sencha.com>
6648 Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
6649 via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
6650 approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
6652 # Asynchronous Loading #
6656 + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
6658 + Best possible debugging experience: error messages come with the exact file name and line number
6661 + Dependencies need to be specified before-hand
6663 ### Method 1: Explicitly include what you need: ###
6666 Ext.require({String/Array} expressions);
6668 // Example: Single alias
6669 Ext.require('widget.window');
6671 // Example: Single class name
6672 Ext.require('Ext.window.Window');
6674 // Example: Multiple aliases / class names mix
6675 Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
6678 Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
6680 ### Method 2: Explicitly exclude what you don't need: ###
6682 // Syntax: Note that it must be in this chaining format.
6683 Ext.exclude({String/Array} expressions)
6684 .require({String/Array} expressions);
6686 // Include everything except Ext.data.*
6687 Ext.exclude('Ext.data.*').require('*');Â
6689 // Include all widgets except widget.checkbox*,
6690 // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
6691 Ext.exclude('widget.checkbox*').require('widget.*');
6693 # Synchronous Loading on Demand #
6696 + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
6700 + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
6701 + Must be from the same domain due to XHR restriction
6702 + Need a web server, same reason as above
6704 There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
6706 Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
6708 Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
6710 Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
6712 Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
6713 existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
6714 class and all its dependencies.
6716 # Hybrid Loading - The Best of Both Worlds #
6718 It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
6720 ### Step 1: Start writing your application using synchronous approach. Ext.Loader will automatically fetch all
6721 dependencies on demand as they're needed during run-time. For example: ###
6723 Ext.onReady(function(){
6724 var window = Ext.createWidget('window', {
6731 title: 'Hello Dialog',
6733 title: 'Navigation',
6748 ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
6750 [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
6752 [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
6754 Simply copy and paste the suggested code above `Ext.onReady`, i.e:
6756 Ext.require('Ext.window.Window');
6757 Ext.require('Ext.layout.container.Border');
6761 Everything should now load via asynchronous mode.
6765 It's important to note that dynamic loading should only be used during development on your local machines.
6766 During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
6767 the whole process of transitioning from / to between development / maintenance and production as easy as
6768 possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
6769 needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
6770 then include it on top of your application.
6772 This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
6778 (function(Manager, Class, flexSetter, alias) {
6781 dependencyProperties = ['extend', 'mixins', 'requires'],
6784 Loader = Ext.Loader = {
6788 documentHead: typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
6791 * Flag indicating whether there are still files being loaded
6797 * Maintain the queue for all dependencies. Each item in the array is an object of the format:
6799 * requires: [...], // The required classes for this queue item
6800 * callback: function() { ... } // The function to execute when all classes specified in requires exist
6807 * Maintain the list of files that have already been handled so that they never get double-loaded
6813 * Maintain the list of listeners to execute when all required scripts are fully loaded
6819 * Contains optional dependencies to be loaded last
6822 optionalRequires: [],
6825 * Map of fully qualified class names to an array of dependent classes.
6841 hasFileLoadError: false,
6846 classNameToFilePathMap: {},
6849 * An array of class names to keep track of the dependency loading order.
6850 * This is not guaranteed to be the same everytime due to the asynchronous
6851 * nature of the Loader.
6864 * Whether or not to enable the dynamic dependency loading feature
6866 * @cfg {Boolean} enabled
6871 * @cfg {Boolean} disableCaching
6872 * Appends current timestamp to script files to prevent caching
6875 disableCaching: true,
6878 * @cfg {String} disableCachingParam
6879 * The get parameter name for the cache buster's timestamp.
6882 disableCachingParam: '_dc',
6885 * @cfg {Object} paths
6886 * The mapping from namespaces to file paths
6888 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
6889 // loaded from ./layout/Container.js
6891 'My': './src/my_own_folder' // My.layout.Container will be loaded from
6892 // ./src/my_own_folder/layout/Container.js
6894 * Note that all relative paths are relative to the current HTML document.
6895 * If not being specified, for example, <code>Other.awesome.Class</code>
6896 * will simply be loaded from <code>./Other/awesome/Class.js</code>
6904 * Set the configuration for the loader. This should be called right after ext-core.js
6905 * (or ext-core-debug.js) is included in the page, i.e:
6907 <script type="text/javascript" src="ext-core-debug.js"></script>
6908 <script type="text/javascript">
6909 Ext.Loader.setConfig({
6916 <script type="text/javascript">
6919 Ext.onReady(function() {
6920 // application code here
6924 * Refer to {@link Ext.Loader#configs} for the list of possible properties
6926 * @param {Object} config The config object to override the default values in {@link Ext.Loader#config}
6927 * @return {Ext.Loader} this
6930 setConfig: function(name, value) {
6931 if (Ext.isObject(name) && arguments.length === 1) {
6932 Ext.Object.merge(this.config, name);
6935 this.config[name] = (Ext.isObject(value)) ? Ext.Object.merge(this.config[name], value) : value;
6942 * Get the config value corresponding to the specified name. If no name is given, will return the config object
6943 * @param {String} name The config property name
6944 * @return {Object/Mixed}
6946 getConfig: function(name) {
6948 return this.config[name];
6955 * Sets the path of a namespace.
6958 Ext.Loader.setPath('Ext', '.');
6960 * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
6961 * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
6962 * @return {Ext.Loader} this
6966 setPath: flexSetter(function(name, path) {
6967 this.config.paths[name] = path;
6973 * Translates a className to a file path by adding the
6974 * the proper prefix and converting the .'s to /'s. For example:
6976 Ext.Loader.setPath('My', '/path/to/My');
6978 alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
6980 * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
6982 Ext.Loader.setPath({
6983 'My': '/path/to/lib',
6984 'My.awesome': '/other/path/for/awesome/stuff',
6985 'My.awesome.more': '/more/awesome/path'
6988 alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
6990 alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
6992 alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
6994 alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
6996 * @param {String} className
6997 * @return {String} path
7000 getPath: function(className) {
7002 paths = this.config.paths,
7003 prefix = this.getPrefix(className);
7005 if (prefix.length > 0) {
7006 if (prefix === className) {
7007 return paths[prefix];
7010 path = paths[prefix];
7011 className = className.substring(prefix.length + 1);
7014 if (path.length > 0) {
7018 return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
7023 * @param {String} className
7025 getPrefix: function(className) {
7026 var paths = this.config.paths,
7027 prefix, deepestPrefix = '';
7029 if (paths.hasOwnProperty(className)) {
7033 for (prefix in paths) {
7034 if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
7035 if (prefix.length > deepestPrefix.length) {
7036 deepestPrefix = prefix;
7041 return deepestPrefix;
7045 * Refresh all items in the queue. If all dependencies for an item exist during looping,
7046 * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
7050 refreshQueue: function() {
7051 var ln = this.queue.length,
7052 i, item, j, requires;
7055 this.triggerReady();
7059 for (i = 0; i < ln; i++) {
7060 item = this.queue[i];
7063 requires = item.requires;
7065 // Don't bother checking when the number of files loaded
7066 // is still less than the array length
7067 if (requires.length > this.numLoadedFiles) {
7074 if (Manager.isCreated(requires[j])) {
7075 // Take out from the queue
7076 requires.splice(j, 1);
7081 } while (j < requires.length);
7083 if (item.requires.length === 0) {
7084 this.queue.splice(i, 1);
7085 item.callback.call(item.scope);
7086 this.refreshQueue();
7096 * Inject a script element to document's head, call onLoad and onError accordingly
7099 injectScriptElement: function(url, onLoad, onError, scope) {
7100 var script = document.createElement('script'),
7102 onLoadFn = function() {
7103 me.cleanupScriptElement(script);
7106 onErrorFn = function() {
7107 me.cleanupScriptElement(script);
7108 onError.call(scope);
7111 script.type = 'text/javascript';
7113 script.onload = onLoadFn;
7114 script.onerror = onErrorFn;
7115 script.onreadystatechange = function() {
7116 if (this.readyState === 'loaded' || this.readyState === 'complete') {
7121 this.documentHead.appendChild(script);
7129 cleanupScriptElement: function(script) {
7130 script.onload = null;
7131 script.onreadystatechange = null;
7132 script.onerror = null;
7138 * Load a script file, supports both asynchronous and synchronous approaches
7140 * @param {String} url
7141 * @param {Function} onLoad
7142 * @param {Scope} scope
7143 * @param {Boolean} synchronous
7146 loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
7148 noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
7149 fileName = url.split('/').pop(),
7150 isCrossOriginRestricted = false,
7151 xhr, status, onScriptError;
7153 scope = scope || this;
7155 this.isLoading = true;
7158 onScriptError = function() {
7159 onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
7162 if (!Ext.isReady && Ext.onDocumentReady) {
7163 Ext.onDocumentReady(function() {
7164 me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
7168 this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
7172 if (typeof XMLHttpRequest !== 'undefined') {
7173 xhr = new XMLHttpRequest();
7175 xhr = new ActiveXObject('Microsoft.XMLHTTP');
7179 xhr.open('GET', noCacheUrl, false);
7182 isCrossOriginRestricted = true;
7185 status = (xhr.status === 1223) ? 204 : xhr.status;
7187 if (!isCrossOriginRestricted) {
7188 isCrossOriginRestricted = (status === 0);
7191 if (isCrossOriginRestricted
7193 onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
7194 "being loaded from a different domain or from the local file system whereby cross origin " +
7195 "requests are not allowed due to security reasons. Use asynchronous loading with " +
7196 "Ext.require instead.", synchronous);
7198 else if (status >= 200 && status < 300
7200 // Firebug friendly, file names are still shown even though they're eval'ed code
7201 new Function(xhr.responseText + "\n//@ sourceURL=" + fileName)();
7206 onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
7207 "verify that the file exists. " +
7208 "XHR status code: " + status, synchronous);
7211 // Prevent potential IE memory leak
7217 * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
7218 * Can be chained with more `require` and `exclude` methods, eg:
7220 Ext.exclude('Ext.data.*').require('*');
7222 Ext.exclude('widget.button*').require('widget.*');
7224 * @param {Array} excludes
7225 * @return {Object} object contains `require` method for chaining
7228 exclude: function(excludes) {
7232 require: function(expressions, fn, scope) {
7233 return me.require(expressions, fn, scope, excludes);
7236 syncRequire: function(expressions, fn, scope) {
7237 return me.syncRequire(expressions, fn, scope, excludes);
7243 * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
7244 * @param {String/Array} expressions Can either be a string or an array of string
7245 * @param {Function} fn (Optional) The callback function
7246 * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
7247 * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
7250 syncRequire: function() {
7251 this.syncModeEnabled = true;
7252 this.require.apply(this, arguments);
7253 this.refreshQueue();
7254 this.syncModeEnabled = false;
7258 * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
7259 * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
7260 * @param {String/Array} expressions Can either be a string or an array of string
7261 * @param {Function} fn (Optional) The callback function
7262 * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
7263 * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
7266 require: function(expressions, fn, scope, excludes) {
7267 var filePath, expression, exclude, className, excluded = {},
7268 excludedClassNames = [],
7269 possibleClassNames = [],
7270 possibleClassName, classNames = [],
7273 expressions = Ext.Array.from(expressions);
7274 excludes = Ext.Array.from(excludes);
7276 fn = fn || Ext.emptyFn;
7278 scope = scope || Ext.global;
7280 for (i = 0, ln = excludes.length; i < ln; i++) {
7281 exclude = excludes[i];
7283 if (typeof exclude === 'string' && exclude.length > 0) {
7284 excludedClassNames = Manager.getNamesByExpression(exclude);
7286 for (j = 0, subLn = excludedClassNames.length; j < subLn; j++) {
7287 excluded[excludedClassNames[j]] = true;
7292 for (i = 0, ln = expressions.length; i < ln; i++) {
7293 expression = expressions[i];
7295 if (typeof expression === 'string' && expression.length > 0) {
7296 possibleClassNames = Manager.getNamesByExpression(expression);
7298 for (j = 0, subLn = possibleClassNames.length; j < subLn; j++) {
7299 possibleClassName = possibleClassNames[j];
7301 if (!excluded.hasOwnProperty(possibleClassName) && !Manager.isCreated(possibleClassName)) {
7302 Ext.Array.include(classNames, possibleClassName);
7308 // If the dynamic dependency feature is not being used, throw an error
7309 // if the dependencies are not defined
7310 if (!this.config.enabled) {
7311 if (classNames.length > 0) {
7313 sourceClass: "Ext.Loader",
7314 sourceMethod: "require",
7315 msg: "Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
7316 "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')
7321 if (classNames.length === 0) {
7327 requires: classNames,
7332 classNames = classNames.slice();
7334 for (i = 0, ln = classNames.length; i < ln; i++) {
7335 className = classNames[i];
7337 if (!this.isFileLoaded.hasOwnProperty(className)) {
7338 this.isFileLoaded[className] = false;
7340 filePath = this.getPath(className);
7342 this.classNameToFilePathMap[className] = filePath;
7344 this.numPendingFiles++;
7346 this.loadScriptFile(
7348 Ext.Function.pass(this.onFileLoaded, [className, filePath], this),
7349 Ext.Function.pass(this.onFileLoadError, [className, filePath]),
7351 this.syncModeEnabled
7361 * @param {String} className
7362 * @param {String} filePath
7364 onFileLoaded: function(className, filePath) {
7365 this.numLoadedFiles++;
7367 this.isFileLoaded[className] = true;
7369 this.numPendingFiles--;
7371 if (this.numPendingFiles === 0) {
7372 this.refreshQueue();
7375 if (this.numPendingFiles <= 1) {
7376 window.status = "Finished loading all dependencies, onReady fired!";
7379 window.status = "Loading dependencies, " + this.numPendingFiles + " files left...";
7382 if (!this.syncModeEnabled && this.numPendingFiles === 0 && this.isLoading && !this.hasFileLoadError) {
7383 var queue = this.queue,
7385 i, ln, j, subLn, missingClasses = [], missingPaths = [];
7387 for (i = 0, ln = queue.length; i < ln; i++) {
7388 requires = queue[i].requires;
7390 for (j = 0, subLn = requires.length; j < ln; j++) {
7391 if (this.isFileLoaded[requires[j]]) {
7392 missingClasses.push(requires[j]);
7397 if (missingClasses.length < 1) {
7401 missingClasses = Ext.Array.filter(missingClasses, function(item) {
7402 return !this.requiresMap.hasOwnProperty(item);
7405 for (i = 0,ln = missingClasses.length; i < ln; i++) {
7406 missingPaths.push(this.classNameToFilePathMap[missingClasses[i]]);
7410 sourceClass: "Ext.Loader",
7411 sourceMethod: "onFileLoaded",
7412 msg: "The following classes are not declared even if their files have been " +
7413 "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " +
7414 "corresponding files for possible typos: '" + missingPaths.join("', '") + "'"
7422 onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
7423 this.numPendingFiles--;
7424 this.hasFileLoadError = true;
7427 sourceClass: "Ext.Loader",
7428 classToLoad: className,
7430 loadingType: isSynchronous ? 'synchronous' : 'async',
7438 addOptionalRequires: function(requires) {
7439 var optionalRequires = this.optionalRequires,
7442 requires = Ext.Array.from(requires);
7444 for (i = 0, ln = requires.length; i < ln; i++) {
7445 require = requires[i];
7447 Ext.Array.include(optionalRequires, require);
7456 triggerReady: function(force) {
7457 var readyListeners = this.readyListeners,
7458 optionalRequires, listener;
7460 if (this.isLoading || force) {
7461 this.isLoading = false;
7463 if (this.optionalRequires.length) {
7464 // Clone then empty the array to eliminate potential recursive loop issue
7465 optionalRequires = Ext.Array.clone(this.optionalRequires);
7467 // Empty the original array
7468 this.optionalRequires.length = 0;
7470 this.require(optionalRequires, Ext.Function.pass(this.triggerReady, [true], this), this);
7474 while (readyListeners.length) {
7475 listener = readyListeners.shift();
7476 listener.fn.call(listener.scope);
7478 if (this.isLoading) {
7488 * Add a new listener to be executed when all required scripts are fully loaded
7490 * @param {Function} fn The function callback to be executed
7491 * @param {Object} scope The execution scope (<code>this</code>) of the callback function
7492 * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
7494 onReady: function(fn, scope, withDomReady, options) {
7497 if (withDomReady !== false && Ext.onDocumentReady) {
7501 Ext.onDocumentReady(oldFn, scope, options);
7505 if (!this.isLoading) {
7509 this.readyListeners.push({
7518 * @param {String} className
7520 historyPush: function(className) {
7521 if (className && this.isFileLoaded.hasOwnProperty(className)) {
7522 Ext.Array.include(this.history, className);
7530 * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
7531 * {@link Ext.Loader} for examples.
7535 Ext.require = alias(Loader, 'require');
7538 * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
7541 * @method syncRequire
7543 Ext.syncRequire = alias(Loader, 'syncRequire');
7546 * Convenient shortcut to {@link Ext.Loader#exclude}
7550 Ext.exclude = alias(Loader, 'exclude');
7556 Ext.onReady = function(fn, scope, options) {
7557 Loader.onReady(fn, scope, true, options);
7560 Class.registerPreprocessor('loader', function(cls, data, continueFn) {
7563 className = Manager.getName(cls),
7564 i, j, ln, subLn, value, propertyName, propertyValue;
7567 Basically loop through the dependencyProperties, look for string class names and push
7568 them into a stack, regardless of whether the property's value is a string, array or object. For example:
7570 extend: 'Ext.MyClass',
7571 requires: ['Ext.some.OtherClass'],
7573 observable: 'Ext.util.Observable';
7576 which will later be transformed into:
7578 extend: Ext.MyClass,
7579 requires: [Ext.some.OtherClass],
7581 observable: Ext.util.Observable;
7586 for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
7587 propertyName = dependencyProperties[i];
7589 if (data.hasOwnProperty(propertyName)) {
7590 propertyValue = data[propertyName];
7592 if (typeof propertyValue === 'string') {
7593 dependencies.push(propertyValue);
7595 else if (propertyValue instanceof Array) {
7596 for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
7597 value = propertyValue[j];
7599 if (typeof value === 'string') {
7600 dependencies.push(value);
7605 for (j in propertyValue) {
7606 if (propertyValue.hasOwnProperty(j)) {
7607 value = propertyValue[j];
7609 if (typeof value === 'string') {
7610 dependencies.push(value);
7618 if (dependencies.length === 0) {
7619 // Loader.historyPush(className);
7623 var deadlockPath = [],
7624 requiresMap = Loader.requiresMap,
7628 Automatically detect deadlocks before-hand,
7629 will throw an error with detailed path for ease of debugging. Examples of deadlock cases:
7631 - A extends B, then B extends A
7632 - A requires B, B requires C, then C requires A
7634 The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks
7635 no matter how deep the path is.
7639 requiresMap[className] = dependencies;
7641 detectDeadlock = function(cls) {
7642 deadlockPath.push(cls);
7644 if (requiresMap[cls]) {
7645 if (Ext.Array.contains(requiresMap[cls], className)) {
7647 sourceClass: "Ext.Loader",
7648 msg: "Deadlock detected while loading dependencies! '" + className + "' and '" +
7649 deadlockPath[1] + "' " + "mutually require each other. Path: " +
7650 deadlockPath.join(' -> ') + " -> " + deadlockPath[0]
7654 for (i = 0, ln = requiresMap[cls].length; i < ln; i++) {
7655 detectDeadlock(requiresMap[cls][i]);
7660 detectDeadlock(className);
7664 Loader.require(dependencies, function() {
7665 for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
7666 propertyName = dependencyProperties[i];
7668 if (data.hasOwnProperty(propertyName)) {
7669 propertyValue = data[propertyName];
7671 if (typeof propertyValue === 'string') {
7672 data[propertyName] = Manager.get(propertyValue);
7674 else if (propertyValue instanceof Array) {
7675 for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
7676 value = propertyValue[j];
7678 if (typeof value === 'string') {
7679 data[propertyName][j] = Manager.get(value);
7684 for (var k in propertyValue) {
7685 if (propertyValue.hasOwnProperty(k)) {
7686 value = propertyValue[k];
7688 if (typeof value === 'string') {
7689 data[propertyName][k] = Manager.get(value);
7697 continueFn.call(me, cls, data);
7703 Class.setDefaultPreprocessorPosition('loader', 'after', 'className');
7705 Manager.registerPostprocessor('uses', function(name, cls, data) {
7706 var uses = Ext.Array.from(data.uses),
7710 for (i = 0, ln = uses.length; i < ln; i++) {
7713 if (typeof item === 'string') {
7718 Loader.addOptionalRequires(items);
7721 Manager.setDefaultPostprocessorPosition('uses', 'last');
7723 })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias);
7730 A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
7731 errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
7732 uses the Ext 4 class system, the Error class can automatically add the source class and method from which
7733 the error was raised. It also includes logic to automatically log the eroor to the console, if available,
7734 with additional metadata about the error. In all cases, the error will always be thrown at the end so that
7735 execution will halt.
7737 Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
7738 handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
7739 although in a real application it's usually a better idea to override the handling function and perform
7740 logging or some other method of reporting the errors in a way that is meaningful to the application.
7742 At its simplest you can simply raise an error as a simple string from within any code:
7746 Ext.Error.raise('Something bad happened!');
7748 If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
7749 displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
7750 additional metadata about the error being raised. The {@link #raise} method can also take a config object.
7751 In this form the `msg` attribute becomes the error description, and any other data added to the config gets
7752 added to the error object and, if the console is available, logged to the console for inspection.
7756 Ext.define('Ext.Foo', {
7757 doSomething: function(option){
7758 if (someCondition === false) {
7760 msg: 'You cannot do that!',
7761 option: option, // whatever was passed into the method
7762 'error code': 100 // other arbitrary info
7768 If a console is available (that supports the `console.dir` function) you'll see console output like:
7770 An error was raised with the following data:
7771 option: Object { foo: "bar"}
7774 msg: "You cannot do that!"
7775 sourceClass: "Ext.Foo"
7776 sourceMethod: "doSomething"
7778 uncaught exception: You cannot do that!
7780 As you can see, the error will report exactly where it was raised and will include as much information as the
7781 raising code can usefully provide.
7783 If you want to handle all application errors globally you can simply override the static {@link handle} method
7784 and provide whatever handling logic you need. If the method returns true then the error is considered handled
7785 and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
7789 Ext.Error.handle = function(err) {
7790 if (err.someProperty == 'NotReallyAnError') {
7791 // maybe log something to the application here if applicable
7794 // any non-true return value (including none) will cause the error to be thrown
7797 * Create a new Error object
7798 * @param {Object} config The config object
7800 * @author Brian Moeskau <brian@sencha.com>
7801 * @docauthor Brian Moeskau <brian@sencha.com>
7803 Ext.Error = Ext.extend(Error, {
7807 Static flag that can be used to globally disable error reporting to the browser if set to true
7808 (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
7809 and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
7810 be preferable to supply a custom error {@link #handle handling} function instead.
7814 Ext.Error.ignore = true;
7823 Static flag that can be used to globally control error notification to the user. Unlike
7824 Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
7825 set to false to disable the alert notification (default is true for IE6 and IE7).
7827 Only the first error will generate an alert. Internally this flag is set to false when the
7828 first error occurs prior to displaying the alert.
7830 This flag is not used in a release build.
7834 Ext.Error.notify = false;
7839 //notify: Ext.isIE6 || Ext.isIE7,
7842 Raise an error that can include additional data and supports automatic console logging if available.
7843 You can pass a string error message or an object with the `msg` attribute which will be used as the
7844 error message. The object can contain any other name-value attributes (or objects) to be logged
7845 along with the error.
7847 Note that after displaying the error message a JavaScript error will ultimately be thrown so that
7848 execution will halt.
7852 Ext.Error.raise('A simple string error message');
7856 Ext.define('Ext.Foo', {
7857 doSomething: function(option){
7858 if (someCondition === false) {
7860 msg: 'You cannot do that!',
7861 option: option, // whatever was passed into the method
7862 'error code': 100 // other arbitrary info
7867 * @param {String/Object} err The error message string, or an object containing the
7868 * attribute "msg" that will be used as the error message. Any other data included in
7869 * the object will also be logged to the browser console, if available.
7873 raise: function(err){
7875 if (Ext.isString(err)) {
7879 var method = this.raise.caller;
7883 err.sourceMethod = method.$name;
7885 if (method.$owner) {
7886 err.sourceClass = method.$owner.$className;
7890 if (Ext.Error.handle(err) !== true) {
7891 var msg = Ext.Error.prototype.toString.call(err);
7900 throw new Ext.Error(err);
7905 Globally handle any Ext errors that may be raised, optionally providing custom logic to
7906 handle different errors individually. Return true from the function to bypass throwing the
7907 error to the browser, otherwise the error will be thrown and execution will halt.
7911 Ext.Error.handle = function(err) {
7912 if (err.someProperty == 'NotReallyAnError') {
7913 // maybe log something to the application here if applicable
7916 // any non-true return value (including none) will cause the error to be thrown
7919 * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes
7920 * that were originally raised with it, plus properties about the method and class from which
7921 * the error originated (if raised from a class that uses the Ext 4 class system).
7926 return Ext.Error.ignore;
7930 // This is the standard property that is the name of the constructor.
7935 * @param {String/Object} config The error message string, or an object containing the
7936 * attribute "msg" that will be used as the error message. Any other data included in
7937 * the object will be applied to the error instance and logged to the browser console, if available.
7939 constructor: function(config){
7940 if (Ext.isString(config)) {
7941 config = { msg: config };
7946 Ext.apply(me, config);
7948 me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
7949 // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
7953 Provides a custom string representation of the error object. This is an override of the base JavaScript
7954 `Object.toString` method, which is useful so that when logged to the browser console, an error object will
7955 be displayed with a useful message instead of `[object Object]`, the default `toString` result.
7957 The default implementation will include the error message along with the raising class and method, if available,
7958 but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
7959 a particular error instance, if you want to provide a custom description that will show up in the console.
7961 * @return {String} The error message. If raised from within the Ext 4 class system, the error message
7962 * will also include the raising class and method names, if available.
7964 toString: function(){
7966 className = me.className ? me.className : '',
7967 methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
7968 msg = me.msg || '(No description provided)';
7970 return className + methodName + msg;
7975 * This mechanism is used to notify the user of the first error encountered on the page. This
7976 * was previously internal to Ext.Error.raise and is a desirable feature since errors often
7977 * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
7978 * where exceptions are handled in a try/catch.
7981 var prevOnError, timer, errors = 0,
7982 extraordinarilyBad = /(out of stack)|(too much recursion)|(stack overflow)|(out of memory)/i,
7985 if (typeof window === 'undefined') {
7986 return; // build system or some such environment...
7989 // This method is called to notify the user of the current error status.
7990 function notify () {
7991 var counters = Ext.log.counters,
7992 supports = Ext.supports,
7993 hasOnError = supports && supports.WindowOnError; // TODO - timing
7995 // Put log counters to the status bar (for most browsers):
7996 if (counters && (counters.error + counters.warn + counters.info + counters.log)) {
7997 var msg = [ 'Logged Errors:',counters.error, 'Warnings:',counters.warn,
7998 'Info:',counters.info, 'Log:',counters.log].join(' ');
8000 msg = '*** Errors: ' + errors + ' - ' + msg;
8001 } else if (counters.error) {
8007 // Display an alert on the first error:
8008 if (!Ext.isDefined(Ext.Error.notify)) {
8009 Ext.Error.notify = Ext.isIE6 || Ext.isIE7; // TODO - timing
8011 if (Ext.Error.notify && (hasOnError ? errors : (counters && counters.error))) {
8012 Ext.Error.notify = false;
8015 win.clearInterval(timer); // ticks can queue up so stop...
8019 alert('Unhandled error on page: See console or log');
8024 // Sets up polling loop. This is the only way to know about errors in some browsers
8025 // (Opera/Safari) and is the only way to update the status bar for warnings and other
8028 timer = win.setInterval(notify, 1000);
8031 // window.onerror is ideal (esp in IE) because you get full context. This is harmless
8032 // otherwise (never called) which is good because you cannot feature detect it.
8033 prevOnError = win.onerror || Ext.emptyFn;
8034 win.onerror = function (message) {
8037 if (!extraordinarilyBad.test(message)) {
8038 // too much recursion + our alert right now = crash IE
8039 // our polling loop will pick it up even if we don't alert now
8043 return prevOnError.apply(this, arguments);