diff --git a/_base/lang.js b/_base/lang.js index d7b652c92b..5391a35123 100644 --- a/_base/lang.js +++ b/_base/lang.js @@ -1,9 +1,8 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ - // module: + // module: // dojo/_base/lang - // summary: - // This module defines the dojo core Javascript language extensions. - + // summary: + // This module defines Javascript language extensions. has.add("bug-for-in-skips-shadowed", function(){ // if true, the for-in interator skips object properties that exist in Object's prototype (IE 6 - ?) @@ -13,26 +12,21 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ return 1; }); - var empty = {}, - - _extraNames = has("bug-for-in-skips-shadowed") ? "hasOwnProperty.valueOf.isPrototypeOf.propertyIsEnumerable.toLocaleString.toString.constructor".split(".") : [], + var _extraNames = + has("bug-for-in-skips-shadowed") ? + "hasOwnProperty.valueOf.isPrototypeOf.propertyIsEnumerable.toLocaleString.toString.constructor".split(".") : [], _extraLen = _extraNames.length, - _mixin = function(/*Object*/ target, /*Object*/ source){ - // summary: - // Adds all properties and methods of source to target. This addition - // is "prototype extension safe", so that instances of objects - // will not pass along prototype defaults. - var name, s, i; + _mixin = function(dest, source, copyFunc){ + var name, s, i, empty = {}; for(name in source){ - // the "tobj" condition avoid copying properties in "source" - // inherited from Object.prototype. For example, if target has a custom - // toString() method, don't overwrite it with the toString() method - // that source inherited from Object.prototype + // the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source" + // inherited from Object.prototype. For example, if dest has a custom toString() method, + // don't overwrite it with the toString() method that source inherited from Object.prototype s = source[name]; - if(!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))){ - target[name] = s; + if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){ + dest[name] = copyFunc ? copyFunc(s) : s; } } @@ -41,74 +35,22 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ for(i = 0; i < _extraLen; ++i){ name = _extraNames[i]; s = source[name]; - if(!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))){ - target[name] = s; + if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){ + dest[name] = copyFunc ? copyFunc(s) : s; } } } } - return target; // Object + return dest; // Object }, - mixin = function(/*Object*/obj, /*Object...*/props){ - // summary: - // Adds all properties and methods of props to obj and returns the - // (now modified) obj. - // description: - // `lang.mixin` can mix multiple source objects into a - // destination object which is then returned. Unlike regular - // `for...in` iteration, `lang.mixin` is also smart about avoiding - // extensions which other toolkits may unwisely add to the root - // object prototype - // obj: - // The object to mix properties into. Also the return value. - // props: - // One or more objects whose values are successively copied into - // obj. If more than one of these objects contain the same value, - // the one specified last in the function call will "win". - // example: - // make a shallow copy of an object - // | var copy = lang.mixin({}, source); - // example: - // many class constructors often take an object which specifies - // values to be configured on the object. In this case, it is - // often simplest to call `lang.mixin` on the `this` object: - // | dojo.declare("acme.Base", null, { - // | constructor: function(properties){ - // | // property configuration: - // | lang.mixin(this, properties); - // | - // | console.log(this.quip); - // | // ... - // | }, - // | quip: "I wasn't born yesterday, you know - I've seen movies.", - // | // ... - // | }); - // | - // | // create an instance of the class and configure it - // | var b = new acme.Base({quip: "That's what it does!" }); - // example: - // copy in properties from multiple objects - // | var flattened = lang.mixin( - // | { - // | name: "Frylock", - // | braces: true - // | }, - // | { - // | name: "Carl Brutanananadilewski" - // | } - // | ); - // | - // | // will print "Carl Brutanananadilewski" - // | console.log(flattened.name); - // | // will print "true" - // | console.log(flattened.braces); - if(!obj){ obj = {}; } + mixin = function(dest, sources){ + if(!dest){ dest = {}; } for(var i = 1, l = arguments.length; i < l; i++){ - _mixin(obj, arguments[i]); + _mixin(dest, arguments[i]); } - return obj; // Object + return dest; // Object }, getProp = function(/*Array*/parts, /*Boolean*/create, /*Object*/context){ @@ -130,77 +72,16 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ return context; // mixed }, - setObject = function(/*String*/name, /*Object*/value, /*Object?*/context){ - // summary: - // Set a property from a dot-separated string, such as "A.B.C" - // description: - // Useful for longer api chains where you have to test each object in - // the chain, or when you have an object reference in string format. - // Objects are created as needed along `path`. Returns the passed - // value if setting is successful or `undefined` if not. - // name: - // Path to a property, in the form "A.B.C". - // context: - // Optional. Object to use as root of path. Defaults to - // `dojo.global`. - // example: - // set the value of `foo.bar.baz`, regardless of whether - // intermediate objects already exist: - // | lang.setObject("foo.bar.baz", value); - // example: - // without `lang.setObject`, we often see code like this: - // | // ensure that intermediate objects are available - // | if(!obj["parent"]){ obj.parent = {}; } - // | if(!obj.parent["child"]){ obj.parent.child = {}; } - // | // now we can safely set the property - // | obj.parent.child.prop = "some value"; - // whereas with `lang.setObject`, we can shorten that to: - // | lang.setObject("parent.child.prop", "some value", obj); + setObject = function(name, value, context){ var parts = name.split("."), p = parts.pop(), obj = getProp(parts, true, context); return obj && p ? (obj[p] = value) : undefined; // Object }, - getObject = function(/*String*/name, /*Boolean?*/create, /*Object?*/context){ - // summary: - // Get a property from a dot-separated string, such as "A.B.C" - // description: - // Useful for longer api chains where you have to test each object in - // the chain, or when you have an object reference in string format. - // name: - // Path to an property, in the form "A.B.C". - // create: - // Optional. Defaults to `false`. If `true`, Objects will be - // created at any point along the 'path' that is undefined. - // context: - // Optional. Object to use as root of path. Defaults to - // 'dojo.global'. Null may be passed. + getObject = function(name, create, context){ return getProp(name.split("."), create, context); // Object }, - exists = function(/*String*/name, /*Object?*/obj){ - // summary: - // determine if an object supports a given method - // description: - // useful for longer api chains where you have to test each object in - // the chain. Useful for object and method detection. - // name: - // Path to an object, in the form "A.B.C". - // obj: - // Object to use as root of path. Defaults to - // 'dojo.global'. Null may be passed. - // example: - // | // define an object - // | var foo = { - // | bar: { } - // | }; - // | - // | // search the global scope - // | lang.exists("foo.bar"); // true - // | lang.exists("foo.bar.baz"); // false - // | - // | // search from a particular scope - // | lang.exists("bar", foo); // true - // | lang.exists("bar.baz", foo); // false + exists = function(name, obj){ return getObject(name, false, obj) !== undefined; // Boolean }, @@ -208,44 +89,24 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ // Crockford (ish) functions - isString = function(/*anything*/ it){ - // summary: - // Return true if it is a String + isString = function(it){ return (typeof it == "string" || it instanceof String); // Boolean }, - isArray = function(/*anything*/ it){ - // summary: - // Return true if it is an Array. - // Does not work on Arrays created in other windows. + isArray = function(it){ return it && (it instanceof Array || typeof it == "array"); // Boolean }, - isFunction = function(/*anything*/ it){ - // summary: - // Return true if it is a Function + isFunction = function(it){ return opts.call(it) === "[object Function]"; }, - isObject = function(/*anything*/ it){ - // summary: - // Returns true if it is a JavaScript object (or an Array, a Function - // or null) + isObject = function(it){ return it !== undefined && (it === null || typeof it == "object" || isArray(it) || isFunction(it)); // Boolean }, - isArrayLike = function(/*anything*/ it){ - // summary: - // similar to dojo.isArray() but more permissive - // description: - // Doesn't strongly test for "arrayness". Instead, settles for "isn't - // a string or number and has a length property". Arguments objects - // and DOM collections will return true when passed to - // dojo.isArrayLike(), but will return false when passed to - // dojo.isArray(). - // returns: - // If it walks like a duck and quacks like a duck, return `true` + isArrayLike = function(it){ return it && it !== undefined && // Boolean // keep out built-in constructors (Number, String, ...) which have length // properties @@ -254,25 +115,18 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ (isArray(it) || isFinite(it.length)); }, - isAlien = function(/*anything*/ it){ - // summary: - // Returns true if it is a built-in function or some other kind of - // oddball that *should* report as a function but doesn't + isAlien = function(it){ return it && !isFunction(it) && /\{\s*\[native code\]\s*\}/.test(String(it)); // Boolean }, - extend = function(/*Object*/ constructor, /*Object...*/ props){ - // summary: - // Adds all properties and methods of props to constructor's - // prototype, making them available to all instances created with - // constructor. + extend = function(constructor, props){ for(var i=1, l=arguments.length; i 2){ return _hitchArgs.apply(dojo, arguments); // Function } @@ -333,37 +155,6 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ return !scope ? method : function(){ return method.apply(scope, arguments || []); }; // Function }, - /*===== - dojo.delegate = function(obj, props){ - // summary: - // Returns a new object which "looks" to obj for properties which it - // does not have a value for. Optionally takes a bag of properties to - // seed the returned object with initially. - // description: - // This is a small implementaton of the Boodman/Crockford delegation - // pattern in JavaScript. An intermediate object constructor mediates - // the prototype chain for the returned object, using it to delegate - // down to obj for property lookup when object-local lookup fails. - // This can be thought of similarly to ES4's "wrap", save that it does - // not act on types but rather on pure objects. - // obj: - // The object to delegate to for properties not found directly on the - // return object or in props. - // props: - // an object containing properties to assign to the returned object - // returns: - // an Object of anonymous type - // example: - // | var foo = { bar: "baz" }; - // | var thinger = dojo.delegate(foo, { thud: "xyzzy"}); - // | thinger.bar == "baz"; // delegated to foo - // | foo.thud == undefined; // by definition - // | thinger.thud == "xyzzy"; // mixed in from props - // | foo.bar = "thonk"; - // | thinger.bar == "thonk"; // still delegated to foo's bar - } - =====*/ - delegate = (function(){ // boodman/crockford delegation w/ cornford optimization function TMP(){} @@ -378,25 +169,6 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ }; })(), - /*===== - dojo._toArray = function(obj, offset, startWith){ - // summary: - // Converts an array-like object (i.e. arguments, DOMCollection) to an - // array. Returns a new Array with the elements of obj. - // obj: Object - // the object to "arrayify". We expect the object to have, at a - // minimum, a length property which corresponds to integer-indexed - // properties. - // offset: Number? - // the location in obj to start iterating from. Defaults to 0. - // Optional. - // startWith: Array? - // An array to pack with the properties of obj. If provided, - // properties in obj are appended at the end of startWith and - // startWith is the returned array. - } - =====*/ - efficient = function(obj, offset, startWith){ return (startWith||[]).concat(Array.prototype.slice.call(obj, offset||0)); }, @@ -417,167 +189,52 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ })() : efficient, partial = function(/*Function|String*/method /*, ...*/){ - // summary: - // similar to hitch() except that the scope object is left to be - // whatever the execution context eventually becomes. - // description: - // Calling dojo.partial is the functional equivalent of calling: - // | dojo.hitch(null, funcName, ...); var arr = [ null ]; return hitch.apply(dojo, arr.concat(_toArray(arguments))); // Function }, - clone = function(/*anything*/ o){ - // summary: - // Clones objects (including DOM nodes) and all children. - // Warning: do not clone cyclic structures. - if(!o || typeof o != "object" || isFunction(o)){ + clone = function(/*anything*/ src){ + if(!src || typeof src != "object" || isFunction(src)){ // null, undefined, any non-object, or function - return o; // anything + return src; // anything } - if(o.nodeType && "cloneNode" in o){ + if(src.nodeType && "cloneNode" in src){ // DOM Node - return o.cloneNode(true); // Node + return src.cloneNode(true); // Node } - if(o instanceof Date){ + if(src instanceof Date){ // Date - return new Date(o.getTime()); // Date + return new Date(src.getTime()); // Date } - if(o instanceof RegExp){ + if(src instanceof RegExp){ // RegExp - return new RegExp(o); // RegExp + return new RegExp(src); // RegExp } var r, i, l, s, name; - if(isArray(o)){ + if(isArray(src)){ // array r = []; - for(i = 0, l = o.length; i < l; ++i){ - if(i in o){ - r.push(clone(o[i])); + for(i = 0, l = src.length; i < l; ++i){ + if(i in src){ + r.push(clone(src[i])); } } // we don't clone functions for performance reasons - // }else if(d.isFunction(o)){ + // }else if(d.isFunction(src)){ // // function - // r = function(){ return o.apply(this, arguments); }; + // r = function(){ return src.apply(this, arguments); }; }else{ // generic objects - r = o.constructor ? new o.constructor() : {}; - } - for(name in o){ - // the "tobj" condition avoid copying properties in "source" - // inherited from Object.prototype. For example, if target has a custom - // toString() method, don't overwrite it with the toString() method - // that source inherited from Object.prototype - s = o[name]; - if(!(name in r) || (r[name] !== s && (!(name in empty) || empty[name] !== s))){ - r[name] = clone(s); - } - } - if(has("bug-for-in-skips-shadowed")){ - var extraNames = _extraNames; - for(i = extraNames.length; i;){ - name = extraNames[--i]; - s = o[name]; - if(!(name in r) || (r[name] !== s && (!(name in empty) || empty[name] !== s))){ - r[name] = s; // functions only, we don't clone them - } - } + r = src.constructor ? new src.constructor() : {}; } - return r; // Object + return _mixin(r, src, clone); }, - /*===== - dojo.trim = function(str){ - // summary: - // Trims whitespace from both sides of the string - // str: String - // String to be trimmed - // returns: String - // Returns the trimmed string - // description: - // This version of trim() was selected for inclusion into the base due - // to its compact size and relatively good performance - // (see [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript) - // Uses String.prototype.trim instead, if available. - // The fastest but longest version of this function is located at - // dojo.string.trim() - return ""; // String - } - =====*/ trim = String.prototype.trim ? function(str){ return str.trim(); } : function(str){ return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, - /*===== - dojo.replace = function(tmpl, map, pattern){ - // summary: - // Performs parameterized substitutions on a string. Throws an - // exception if any parameter is unmatched. - // tmpl: String - // String to be used as a template. - // map: Object|Function - // If an object, it is used as a dictionary to look up substitutions. - // If a function, it is called for every substitution with following - // parameters: a whole match, a name, an offset, and the whole template - // string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace - // for more details). - // pattern: RegEx? - // Optional regular expression objects that overrides the default pattern. - // Must be global and match one item. The default is: /\{([^\}]+)\}/g, - // which matches patterns like that: "{xxx}", where "xxx" is any sequence - // of characters, which doesn't include "}". - // returns: String - // Returns the substituted string. - // example: - // | // uses a dictionary for substitutions: - // | dojo.replace("Hello, {name.first} {name.last} AKA {nick}!", - // | { - // | nick: "Bob", - // | name: { - // | first: "Robert", - // | middle: "X", - // | last: "Cringely" - // | } - // | }); - // | // returns: Hello, Robert Cringely AKA Bob! - // example: - // | // uses an array for substitutions: - // | dojo.replace("Hello, {0} {2}!", - // | ["Robert", "X", "Cringely"]); - // | // returns: Hello, Robert Cringely! - // example: - // | // uses a function for substitutions: - // | function sum(a){ - // | var t = 0; - // | dojo.forEach(a, function(x){ t += x; }); - // | return t; - // | } - // | dojo.replace( - // | "{count} payments averaging {avg} USD per payment.", - // | dojo.hitch( - // | { payments: [11, 16, 12] }, - // | function(_, key){ - // | switch(key){ - // | case "count": return this.payments.length; - // | case "min": return Math.min.apply(Math, this.payments); - // | case "max": return Math.max.apply(Math, this.payments); - // | case "sum": return sum(this.payments); - // | case "avg": return sum(this.payments) / this.payments.length; - // | } - // | } - // | ) - // | ); - // | // prints: 3 payments averaging 13 USD per payment. - // example: - // | // uses an alternative PHP-like pattern for substitutions: - // | dojo.replace("Hello, ${0} ${2}!", - // | ["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g); - // | // returns: Hello, Robert Cringely! - return ""; // String - } - =====*/ _pattern = /\{([^\}]+)\}/g, @@ -612,4 +269,439 @@ define(["./kernel", "../has", "./sniff"], function(dojo, has, sniff){ has("dojo-1x-base") && mixin(dojo, lang); return lang; + + /*===== + dojo._extraNames + // summary: + // Array of strings. Lists property names that must be explicitly processed during for-in interation + // in environments that have has("bug-for-in-skips-shadowed") true. + =====*/ + + /*===== + dojo._mixin = function(dest, source, copyFunc){ + // summary: + // Copies/adds all properties of source to dest; returns dest. + // dest: Object: + // The object to which to copy/add all properties contained in source. + // source: Object: + // The object from which to draw all properties to copy into dest. + // copyFunc: Function?: + // The process used to copy/add a property in source; defaults to the Javascript assignment operator. + // returns: + // dest, as modified + // description: + // All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions + // found in Object.prototype, are copied/added to dest. Copying/adding each particular property is + // delegated to copyFunc (if any); copyFunc defaults to the Javascript assignment operator if not provided. + // Notice that by default, _mixin executes a so-called "shallow copy" and aggregate types are copied/added by reference. + } + =====*/ + + /*===== + dojo.mixin = function(dest, sources){ + // summary: + // Copies/adds all properties of one or more sources to dest; returns dest. + // dest: Object + // The object to which to copy/add all properties contained in source. If dest is falsy, then + // a new object is manufactured before copying/adding properties begins. + // sources: Object... + // One of more objects from which to draw all properties to copy into dest. sources are processed + // left-to-right and if more than one of these objects contain the same property name, the right-most + // value "wins". + // returns: Object + // dest, as modified + // description: + // All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions + // found in Object.prototype, are copied/added from sources to dest. sources are processed left to right. + // The Javascript assignment operator is used to copy/add each property; therefore, by default, mixin + // executes a so-called "shallow copy" and aggregate types are copied/added by reference. + // example: + // make a shallow copy of an object + // | var copy = lang.mixin({}, source); + // example: + // many class constructors often take an object which specifies + // values to be configured on the object. In this case, it is + // often simplest to call `lang.mixin` on the `this` object: + // | dojo.declare("acme.Base", null, { + // | constructor: function(properties){ + // | // property configuration: + // | lang.mixin(this, properties); + // | + // | console.log(this.quip); + // | // ... + // | }, + // | quip: "I wasn't born yesterday, you know - I've seen movies.", + // | // ... + // | }); + // | + // | // create an instance of the class and configure it + // | var b = new acme.Base({quip: "That's what it does!" }); + // example: + // copy in properties from multiple objects + // | var flattened = lang.mixin( + // | { + // | name: "Frylock", + // | braces: true + // | }, + // | { + // | name: "Carl Brutanananadilewski" + // | } + // | ); + // | + // | // will print "Carl Brutanananadilewski" + // | console.log(flattened.name); + // | // will print "true" + // | console.log(flattened.braces); + } + =====*/ + + /*===== + dojo.setObject = function(name, value, context){ + // summary: + // Set a property from a dot-separated string, such as "A.B.C" + // description: + // Useful for longer api chains where you have to test each object in + // the chain, or when you have an object reference in string format. + // Objects are created as needed along `path`. Returns the passed + // value if setting is successful or `undefined` if not. + // name: String + // Path to a property, in the form "A.B.C". + // value: anything + // value or object to place at location given by name + // context: Object? + // Optional. Object to use as root of path. Defaults to + // `dojo.global`. + // example: + // set the value of `foo.bar.baz`, regardless of whether + // intermediate objects already exist: + // | lang.setObject("foo.bar.baz", value); + // example: + // without `lang.setObject`, we often see code like this: + // | // ensure that intermediate objects are available + // | if(!obj["parent"]){ obj.parent = {}; } + // | if(!obj.parent["child"]){ obj.parent.child = {}; } + // | // now we can safely set the property + // | obj.parent.child.prop = "some value"; + // whereas with `lang.setObject`, we can shorten that to: + // | lang.setObject("parent.child.prop", "some value", obj); + } + =====*/ + + /*===== + dojo.getObject = function(name, create, context){ + // summary: + // Get a property from a dot-separated string, such as "A.B.C" + // description: + // Useful for longer api chains where you have to test each object in + // the chain, or when you have an object reference in string format. + // name: String + // Path to an property, in the form "A.B.C". + // create: Boolean? + // Optional. Defaults to `false`. If `true`, Objects will be + // created at any point along the 'path' that is undefined. + // context: Object? + // Optional. Object to use as root of path. Defaults to + // 'dojo.global'. Null may be passed. + } + =====*/ + + /*===== + dojo.exists = function(name, obj){ + // summary: + // determine if an object supports a given method + // description: + // useful for longer api chains where you have to test each object in + // the chain. Useful for object and method detection. + // name: String + // Path to an object, in the form "A.B.C". + // obj: Object? + // Object to use as root of path. Defaults to + // 'dojo.global'. Null may be passed. + // example: + // | // define an object + // | var foo = { + // | bar: { } + // | }; + // | + // | // search the global scope + // | lang.exists("foo.bar"); // true + // | lang.exists("foo.bar.baz"); // false + // | + // | // search from a particular scope + // | lang.exists("bar", foo); // true + // | lang.exists("bar.baz", foo); // false + } + =====*/ + + /*===== + dojo.isString = function(it){ + // summary: + // Return true if it is a String + // it: anything + // Item to test. + } + =====*/ + + /*===== + dojo.isArray = function(it){ + // summary: + // Return true if it is an Array. + // Does not work on Arrays created in other windows. + // it: anything + // Item to test. + } + =====*/ + + /*===== + dojo.isFunction = function(it){ + // summary: + // Return true if it is a Function + // it: anything + // Item to test. + } + =====*/ + + /*===== + dojo.isStringisObject = function(it){ + // summary: + // Returns true if it is a JavaScript object (or an Array, a Function + // or null) + // it: anything + // Item to test. + } + =====*/ + + /*===== + dojo.isArrayLike = function(it){ + // summary: + // similar to dojo.isArray() but more permissive + // it: anything + // Item to test. + // returns: + // If it walks like a duck and quacks like a duck, return `true` + // description: + // Doesn't strongly test for "arrayness". Instead, settles for "isn't + // a string or number and has a length property". Arguments objects + // and DOM collections will return true when passed to + // dojo.isArrayLike(), but will return false when passed to + // dojo.isArray(). + } + =====*/ + + /*===== + dojo.isAlien = function(it){ + // summary: + // Returns true if it is a built-in function or some other kind of + // oddball that *should* report as a function but doesn't + } + =====*/ + + /*===== + dojo.extend = function(constructor, props){ + // summary: + // Adds all properties and methods of props to constructor's + // prototype, making them available to all instances created with + // constructor. + // constructor: Object + // Target constructor to extend. + // props: Object... + // One or more objects to mix into constructor.prototype + } + =====*/ + + /*===== + dojo.hitch = function(scope, method){ + // summary: + // Returns a function that will only ever execute in the a given scope. + // This allows for easy use of object member functions + // in callbacks and other places in which the "this" keyword may + // otherwise not reference the expected scope. + // Any number of default positional arguments may be passed as parameters + // beyond "method". + // Each of these values will be used to "placehold" (similar to curry) + // for the hitched function. + // scope: Object + // The scope to use when method executes. If method is a string, + // scope is also the object containing method. + // method: Function|String... + // A function to be hitched to scope, or the name of the method in + // scope to be hitched. + // example: + // | dojo.hitch(foo, "bar")(); + // runs foo.bar() in the scope of foo + // example: + // | dojo.hitch(foo, myFunction); + // returns a function that runs myFunction in the scope of foo + // example: + // Expansion on the default positional arguments passed along from + // hitch. Passed args are mixed first, additional args after. + // | var foo = { bar: function(a, b, c){ console.log(a, b, c); } }; + // | var fn = dojo.hitch(foo, "bar", 1, 2); + // | fn(3); // logs "1, 2, 3" + // example: + // | var foo = { bar: 2 }; + // | dojo.hitch(foo, function(){ this.bar = 10; })(); + // execute an anonymous function in scope of foo + } + =====*/ + + /*===== + dojo.delegate = function(obj, props){ + // summary: + // Returns a new object which "looks" to obj for properties which it + // does not have a value for. Optionally takes a bag of properties to + // seed the returned object with initially. + // description: + // This is a small implementaton of the Boodman/Crockford delegation + // pattern in JavaScript. An intermediate object constructor mediates + // the prototype chain for the returned object, using it to delegate + // down to obj for property lookup when object-local lookup fails. + // This can be thought of similarly to ES4's "wrap", save that it does + // not act on types but rather on pure objects. + // obj: Object + // The object to delegate to for properties not found directly on the + // return object or in props. + // props: Object... + // an object containing properties to assign to the returned object + // returns: + // an Object of anonymous type + // example: + // | var foo = { bar: "baz" }; + // | var thinger = dojo.delegate(foo, { thud: "xyzzy"}); + // | thinger.bar == "baz"; // delegated to foo + // | foo.thud == undefined; // by definition + // | thinger.thud == "xyzzy"; // mixed in from props + // | foo.bar = "thonk"; + // | thinger.bar == "thonk"; // still delegated to foo's bar + } + =====*/ + + /*===== + dojo.partial = function(method){ + // summary: + // similar to hitch() except that the scope object is left to be + // whatever the execution context eventually becomes. + // method: Function|String + // description: + // Calling dojo.partial is the functional equivalent of calling: + // | dojo.hitch(null, funcName, ...); + } + =====*/ + + /*===== + dojo.trim = function(str){ + // summary: + // Trims whitespace from both sides of the string + // str: String + // String to be trimmed + // returns: String + // Returns the trimmed string + // description: + // This version of trim() was selected for inclusion into the base due + // to its compact size and relatively good performance + // (see [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript) + // Uses String.prototype.trim instead, if available. + // The fastest but longest version of this function is located at + // dojo.string.trim() + } + =====*/ + + /*===== + dojo.clone = function(src){ + // summary: + // Clones objects (including DOM nodes) and all children. + // Warning: do not clone cyclic structures. + // src: + // The object to clone + } + =====*/ + + /*===== + dojo._toArray = function(obj, offset, startWith){ + // summary: + // Converts an array-like object (i.e. arguments, DOMCollection) to an + // array. Returns a new Array with the elements of obj. + // obj: Object + // the object to "arrayify". We expect the object to have, at a + // minimum, a length property which corresponds to integer-indexed + // properties. + // offset: Number? + // the location in obj to start iterating from. Defaults to 0. + // Optional. + // startWith: Array? + // An array to pack with the properties of obj. If provided, + // properties in obj are appended at the end of startWith and + // startWith is the returned array. + } + =====*/ + + /*===== + dojo.replace = function(tmpl, map, pattern){ + // summary: + // Performs parameterized substitutions on a string. Throws an + // exception if any parameter is unmatched. + // tmpl: String + // String to be used as a template. + // map: Object|Function + // If an object, it is used as a dictionary to look up substitutions. + // If a function, it is called for every substitution with following + // parameters: a whole match, a name, an offset, and the whole template + // string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace + // for more details). + // pattern: RegEx? + // Optional regular expression objects that overrides the default pattern. + // Must be global and match one item. The default is: /\{([^\}]+)\}/g, + // which matches patterns like that: "{xxx}", where "xxx" is any sequence + // of characters, which doesn't include "}". + // returns: String + // Returns the substituted string. + // example: + // | // uses a dictionary for substitutions: + // | dojo.replace("Hello, {name.first} {name.last} AKA {nick}!", + // | { + // | nick: "Bob", + // | name: { + // | first: "Robert", + // | middle: "X", + // | last: "Cringely" + // | } + // | }); + // | // returns: Hello, Robert Cringely AKA Bob! + // example: + // | // uses an array for substitutions: + // | dojo.replace("Hello, {0} {2}!", + // | ["Robert", "X", "Cringely"]); + // | // returns: Hello, Robert Cringely! + // example: + // | // uses a function for substitutions: + // | function sum(a){ + // | var t = 0; + // | dojo.forEach(a, function(x){ t += x; }); + // | return t; + // | } + // | dojo.replace( + // | "{count} payments averaging {avg} USD per payment.", + // | dojo.hitch( + // | { payments: [11, 16, 12] }, + // | function(_, key){ + // | switch(key){ + // | case "count": return this.payments.length; + // | case "min": return Math.min.apply(Math, this.payments); + // | case "max": return Math.max.apply(Math, this.payments); + // | case "sum": return sum(this.payments); + // | case "avg": return sum(this.payments) / this.payments.length; + // | } + // | } + // | ) + // | ); + // | // prints: 3 payments averaging 13 USD per payment. + // example: + // | // uses an alternative PHP-like pattern for substitutions: + // | dojo.replace("Hello, ${0} ${2}!", + // | ["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g); + // | // returns: Hello, Robert Cringely! + return ""; // String + } + =====*/ }); +