PageRenderTime 23ms CodeModel.GetById 11ms app.highlight 9ms RepoModel.GetById 0ms app.codeStats 0ms

/ext-4.1.0_b3/docs/source/Function2.html

https://bitbucket.org/srogerf/javascript
HTML | 502 lines | 467 code | 35 blank | 0 comment | 0 complexity | 65b6ce3947856a9ce3135de0d67b7bd8 MD5 | raw file
  1<!DOCTYPE html>
  2<html>
  3<head>
  4  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5  <title>The source code</title>
  6  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  7  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  8  <style type="text/css">
  9    .highlight { display: block; background-color: #ddd; }
 10  </style>
 11  <script type="text/javascript">
 12    function highlight() {
 13      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
 14    }
 15  </script>
 16</head>
 17<body onload="prettyPrint(); highlight();">
 18  <pre class="prettyprint lang-js"><span id='Ext-Function'>/**
 19</span> * @class Ext.Function
 20 *
 21 * A collection of useful static methods to deal with function callbacks
 22 * @singleton
 23 * @alternateClassName Ext.util.Functions
 24 */
 25Ext.Function = {
 26
 27<span id='Ext-Function-method-flexSetter'>    /**
 28</span>     * A very commonly used method throughout the framework. It acts as a wrapper around another method
 29     * which originally accepts 2 arguments for `name` and `value`.
 30     * The wrapped function then allows &quot;flexible&quot; value setting of either:
 31     *
 32     * - `name` and `value` as 2 arguments
 33     * - one single object argument with multiple key - value pairs
 34     *
 35     * For example:
 36     *
 37     *     var setValue = Ext.Function.flexSetter(function(name, value) {
 38     *         this[name] = value;
 39     *     });
 40     *
 41     *     // Afterwards
 42     *     // Setting a single name - value
 43     *     setValue('name1', 'value1');
 44     *
 45     *     // Settings multiple name - value pairs
 46     *     setValue({
 47     *         name1: 'value1',
 48     *         name2: 'value2',
 49     *         name3: 'value3'
 50     *     });
 51     *
 52     * @param {Function} setter
 53     * @returns {Function} flexSetter
 54     */
 55    flexSetter: function(fn) {
 56        return function(a, b) {
 57            var k, i;
 58
 59            if (a === null) {
 60                return this;
 61            }
 62
 63            if (typeof a !== 'string') {
 64                for (k in a) {
 65                    if (a.hasOwnProperty(k)) {
 66                        fn.call(this, k, a[k]);
 67                    }
 68                }
 69
 70                if (Ext.enumerables) {
 71                    for (i = Ext.enumerables.length; i--;) {
 72                        k = Ext.enumerables[i];
 73                        if (a.hasOwnProperty(k)) {
 74                            fn.call(this, k, a[k]);
 75                        }
 76                    }
 77                }
 78            } else {
 79                fn.call(this, a, b);
 80            }
 81
 82            return this;
 83        };
 84    },
 85
 86<span id='Ext-Function-method-bind'>    /**
 87</span>     * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
 88     * overrides arguments for the call. (Defaults to the arguments passed by the caller)
 89     *
 90     * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
 91     *
 92     * @param {Function} fn The function to delegate.
 93     * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
 94     * **If omitted, defaults to the default global environment object (usually the browser window).**
 95     * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
 96     * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
 97     * if a number the args are inserted at the specified position
 98     * @return {Function} The new function
 99     */
100    bind: function(fn, scope, args, appendArgs) {
101        if (arguments.length === 2) {
102            return function() {
103                return fn.apply(scope, arguments);
104            };
105        }
106
107        var method = fn,
108            slice = Array.prototype.slice;
109
110        return function() {
111            var callArgs = args || arguments;
112
113            if (appendArgs === true) {
114                callArgs = slice.call(arguments, 0);
115                callArgs = callArgs.concat(args);
116            }
117            else if (typeof appendArgs == 'number') {
118                callArgs = slice.call(arguments, 0); // copy arguments first
119                Ext.Array.insert(callArgs, appendArgs, args);
120            }
121
122            return method.apply(scope || Ext.global, callArgs);
123        };
124    },
125
126<span id='Ext-Function-method-pass'>    /**
127</span>     * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
128     * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
129     * This is especially useful when creating callbacks.
130     *
131     * For example:
132     *
133     *     var originalFunction = function(){
134     *         alert(Ext.Array.from(arguments).join(' '));
135     *     };
136     *
137     *     var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
138     *
139     *     callback(); // alerts 'Hello World'
140     *     callback('by Me'); // alerts 'Hello World by Me'
141     *
142     * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
143     *
144     * @param {Function} fn The original function
145     * @param {Array} args The arguments to pass to new callback
146     * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
147     * @return {Function} The new callback function
148     */
149    pass: function(fn, args, scope) {
150        if (!Ext.isArray(args)) {
151            if (Ext.isIterable(args)) {
152                args = Ext.Array.clone(args);
153            } else {
154                args = args !== undefined ? [args] : [];
155            }
156        };
157
158        return function() {
159            var fnArgs = [].concat(args);
160            fnArgs.push.apply(fnArgs, arguments);
161            return fn.apply(scope || this, fnArgs);
162        };
163    },
164
165<span id='Ext-Function-method-alias'>    /**
166</span>     * Create an alias to the provided method property with name `methodName` of `object`.
167     * Note that the execution scope will still be bound to the provided `object` itself.
168     *
169     * @param {Object/Function} object
170     * @param {String} methodName
171     * @return {Function} aliasFn
172     */
173    alias: function(object, methodName) {
174        return function() {
175            return object[methodName].apply(object, arguments);
176        };
177    },
178
179<span id='Ext-Function-method-clone'>    /**
180</span>     * Create a &quot;clone&quot; of the provided method. The returned method will call the given
181     * method passing along all arguments and the &quot;this&quot; pointer and return its result.
182     *
183     * @param {Function} method
184     * @return {Function} cloneFn
185     */
186    clone: function(method) {
187        return function() {
188            return method.apply(this, arguments);
189        };
190    },
191
192<span id='Ext-Function-method-createInterceptor'>    /**
193</span>     * Creates an interceptor function. The passed function is called before the original one. If it returns false,
194     * the original one is not called. The resulting function returns the results of the original function.
195     * The passed function is called with the parameters of the original function. Example usage:
196     *
197     *     var sayHi = function(name){
198     *         alert('Hi, ' + name);
199     *     }
200     *
201     *     sayHi('Fred'); // alerts &quot;Hi, Fred&quot;
202     *
203     *     // create a new function that validates input without
204     *     // directly modifying the original function:
205     *     var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
206     *         return name == 'Brian';
207     *     });
208     *
209     *     sayHiToFriend('Fred');  // no alert
210     *     sayHiToFriend('Brian'); // alerts &quot;Hi, Brian&quot;
211     *
212     * @param {Function} origFn The original function.
213     * @param {Function} newFn The function to call before the original
214     * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
215     * **If omitted, defaults to the scope in which the original function is called or the browser window.**
216     * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
217     * @return {Function} The new function
218     */
219    createInterceptor: function(origFn, newFn, scope, returnValue) {
220        var method = origFn;
221        if (!Ext.isFunction(newFn)) {
222            return origFn;
223        }
224        else {
225            return function() {
226                var me = this,
227                    args = arguments;
228                newFn.target = me;
229                newFn.method = origFn;
230                return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null;
231            };
232        }
233    },
234
235<span id='Ext-Function-method-createDelayed'>    /**
236</span>     * Creates a delegate (callback) which, when called, executes after a specific delay.
237     *
238     * @param {Function} fn The function which will be called on a delay when the returned function is called.
239     * Optionally, a replacement (or additional) argument list may be specified.
240     * @param {Number} delay The number of milliseconds to defer execution by whenever called.
241     * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
242     * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
243     * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
244     * if a number the args are inserted at the specified position.
245     * @return {Function} A function which, when called, executes the original function after the specified delay.
246     */
247    createDelayed: function(fn, delay, scope, args, appendArgs) {
248        if (scope || args) {
249            fn = Ext.Function.bind(fn, scope, args, appendArgs);
250        }
251
252        return function() {
253            var me = this,
254                args = Array.prototype.slice.call(arguments);
255
256            setTimeout(function() {
257                fn.apply(me, args);
258            }, delay);
259        };
260    },
261
262<span id='Ext-Function-method-defer'>    /**
263</span>     * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
264     *
265     *     var sayHi = function(name){
266     *         alert('Hi, ' + name);
267     *     }
268     *
269     *     // executes immediately:
270     *     sayHi('Fred');
271     *
272     *     // executes after 2 seconds:
273     *     Ext.Function.defer(sayHi, 2000, this, ['Fred']);
274     *
275     *     // this syntax is sometimes useful for deferring
276     *     // execution of an anonymous function:
277     *     Ext.Function.defer(function(){
278     *         alert('Anonymous');
279     *     }, 100);
280     *
281     * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
282     *
283     * @param {Function} fn The function to defer.
284     * @param {Number} millis The number of milliseconds for the setTimeout call
285     * (if less than or equal to 0 the function is executed immediately)
286     * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
287     * **If omitted, defaults to the browser window.**
288     * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
289     * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
290     * if a number the args are inserted at the specified position
291     * @return {Number} The timeout id that can be used with clearTimeout
292     */
293    defer: function(fn, millis, scope, args, appendArgs) {
294        fn = Ext.Function.bind(fn, scope, args, appendArgs);
295        if (millis &gt; 0) {
296            return setTimeout(fn, millis);
297        }
298        fn();
299        return 0;
300    },
301
302<span id='Ext-Function-method-createSequence'>    /**
303</span>     * Create a combined function call sequence of the original function + the passed function.
304     * The resulting function returns the results of the original function.
305     * The passed function is called with the parameters of the original function. Example usage:
306     *
307     *     var sayHi = function(name){
308     *         alert('Hi, ' + name);
309     *     }
310     *
311     *     sayHi('Fred'); // alerts &quot;Hi, Fred&quot;
312     *
313     *     var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
314     *         alert('Bye, ' + name);
315     *     });
316     *
317     *     sayGoodbye('Fred'); // both alerts show
318     *
319     * @param {Function} originalFn The original function.
320     * @param {Function} newFn The function to sequence
321     * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
322     * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window).
323     * @return {Function} The new function
324     */
325    createSequence: function(originalFn, newFn, scope) {
326        if (!newFn) {
327            return originalFn;
328        }
329        else {
330            return function() {
331                var result = originalFn.apply(this, arguments);
332                newFn.apply(scope || this, arguments);
333                return result;
334            };
335        }
336    },
337
338<span id='Ext-Function-method-createBuffered'>    /**
339</span>     * Creates a delegate function, optionally with a bound scope which, when called, buffers
340     * the execution of the passed function for the configured number of milliseconds.
341     * If called again within that period, the impending invocation will be canceled, and the
342     * timeout period will begin again.
343     *
344     * @param {Function} fn The function to invoke on a buffered timer.
345     * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
346     * function.
347     * @param {Object} scope (optional) The scope (`this` reference) in which
348     * the passed function is executed. If omitted, defaults to the scope specified by the caller.
349     * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
350     * passed by the caller.
351     * @return {Function} A function which invokes the passed function after buffering for the specified time.
352     */
353    createBuffered: function(fn, buffer, scope, args) {
354        var timerId;
355
356        return function() {
357            var callArgs = args || Array.prototype.slice.call(arguments, 0),
358                me = scope || this;
359
360            if (timerId) {
361                clearTimeout(timerId);
362            }
363
364            timerId = setTimeout(function(){
365                fn.apply(me, callArgs);
366            }, buffer);
367        };
368    },
369
370<span id='Ext-Function-method-createThrottled'>    /**
371</span>     * Creates a throttled version of the passed function which, when called repeatedly and
372     * rapidly, invokes the passed function only after a certain interval has elapsed since the
373     * previous invocation.
374     *
375     * This is useful for wrapping functions which may be called repeatedly, such as
376     * a handler of a mouse move event when the processing is expensive.
377     *
378     * @param {Function} fn The function to execute at a regular time interval.
379     * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
380     * @param {Object} scope (optional) The scope (`this` reference) in which
381     * the passed function is executed. If omitted, defaults to the scope specified by the caller.
382     * @returns {Function} A function which invokes the passed function at the specified interval.
383     */
384    createThrottled: function(fn, interval, scope) {
385        var lastCallTime, elapsed, lastArgs, timer, execute = function() {
386            fn.apply(scope || this, lastArgs);
387            lastCallTime = new Date().getTime();
388        };
389
390        return function() {
391            elapsed = new Date().getTime() - lastCallTime;
392            lastArgs = arguments;
393
394            clearTimeout(timer);
395            if (!lastCallTime || (elapsed &gt;= interval)) {
396                execute();
397            } else {
398                timer = setTimeout(execute, interval - elapsed);
399            }
400        };
401    },
402
403<span id='Ext-Function-method-interceptBefore'>    /**
404</span>     * Adds behavior to an existing method that is executed before the
405     * original behavior of the function.  For example:
406     * 
407     *     var soup = {
408     *         contents: [],
409     *         add: function(ingredient) {
410     *             this.contents.push(ingredient);
411     *         }
412     *     };
413     *     Ext.Function.interceptBefore(soup, &quot;add&quot;, function(ingredient){
414     *         if (!this.contents.length &amp;&amp; ingredient !== &quot;water&quot;) {
415     *             // Always add water to start with
416     *             this.contents.push(&quot;water&quot;);
417     *         }
418     *     });
419     *     soup.add(&quot;onions&quot;);
420     *     soup.add(&quot;salt&quot;);
421     *     soup.contents; // will contain: water, onions, salt
422     * 
423     * @param {Object} object The target object
424     * @param {String} methodName Name of the method to override
425     * @param {Function} fn Function with the new behavior.  It will
426     * be called with the same arguments as the original method.  The
427     * return value of this function will be the return value of the
428     * new method.
429     * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
430     * @return {Function} The new function just created.
431     */
432    interceptBefore: function(object, methodName, fn, scope) {
433        var method = object[methodName] || Ext.emptyFn;
434
435        return (object[methodName] = function() {
436            var ret = fn.apply(scope || this, arguments);
437            method.apply(this, arguments);
438
439            return ret;
440        });
441    },
442
443<span id='Ext-Function-method-interceptAfter'>    /**
444</span>     * Adds behavior to an existing method that is executed after the
445     * original behavior of the function.  For example:
446     * 
447     *     var soup = {
448     *         contents: [],
449     *         add: function(ingredient) {
450     *             this.contents.push(ingredient);
451     *         }
452     *     };
453     *     Ext.Function.interceptAfter(soup, &quot;add&quot;, function(ingredient){
454     *         // Always add a bit of extra salt
455     *         this.contents.push(&quot;salt&quot;);
456     *     });
457     *     soup.add(&quot;water&quot;);
458     *     soup.add(&quot;onions&quot;);
459     *     soup.contents; // will contain: water, salt, onions, salt
460     * 
461     * @param {Object} object The target object
462     * @param {String} methodName Name of the method to override
463     * @param {Function} fn Function with the new behavior.  It will
464     * be called with the same arguments as the original method.  The
465     * return value of this function will be the return value of the
466     * new method.
467     * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
468     * @return {Function} The new function just created.
469     */
470    interceptAfter: function(object, methodName, fn, scope) {
471        var method = object[methodName] || Ext.emptyFn;
472
473        return (object[methodName] = function() {
474            method.apply(this, arguments);
475            return fn.apply(scope || this, arguments);
476        });
477    }
478};
479
480<span id='Ext-method-defer'>/**
481</span> * @method
482 * @member Ext
483 * @inheritdoc Ext.Function#defer
484 */
485Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
486
487<span id='Ext-method-pass'>/**
488</span> * @method
489 * @member Ext
490 * @inheritdoc Ext.Function#pass
491 */
492Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
493
494<span id='Ext-method-bind'>/**
495</span> * @method
496 * @member Ext
497 * @inheritdoc Ext.Function#bind
498 */
499Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
500</pre>
501</body>
502</html>