Rename <Type>.from to <Type>.convert
[mootools.git] / Docs / Types / Function.md
blobd9b1f5670d42bbf79e37cf2dc41a7d7c1a59baeb
1 Type: Function {#Function}
2 ==========================
4 Function Methods.
6 ### See Also:
8 - [MDN Function][]
12 Function: Function.convert {#Function:Function:convert}
13 -------------------------------------------------
15 If the passed argument is a function, it will return itself. Otherwise, it will return a function that returns the passed argument.
17 ### Syntax:
19         var foo = Function.convert(obj);
21 ### Arguments:
23 1. obj - (*mixed*) If this argument is a function, it will simply return itself. Otherwise, an object you wish to convert into a function that returns the argument.
25 ### Returns:
27 * (*function*) Either the passed function or an anonymous function that returns the passed argument.
29 ### Examples:
31         var fn = Function.convert(42);
32         alert(fn());    // alerts '42'
34         var fn2 = Function.convert(fn);
35         alert(fn2());   // alerts '42'
37 ### Notes:
39 This function is equivalent to the following deprecated MooTools 1.2 methods:
41         var fn1 = Function.convert();           // equivalent to var fn1 = function(){};
42         var fn2 = Function.convert(foo);        // equivalent to var fn2 = function(){ return foo; };
45 Function: Function.attempt {#Function:Function-attempt}
46 -------------------------------------------------------
48 Tries to execute a number of functions. Returns immediately the return value of the first non-failed function without executing successive functions, or null.
50 ### Syntax:
52         Function.attempt(fn[, fn, fn, fn, ...]);
54 ### Arguments:
56 * fn   - (*function*) Any number of functions to execute.
58 ### Returns:
60 * (*mixed*) Standard return of the called function.
61 * (*null*) `null` if all the passed functions fail.
63 ### Examples:
65         var result = Function.attempt(function(){
66                 return some.made.up.object;
67         }, function(){
68                 return jibberish.that.doesnt.exists;
69         }, function(){
70                 return false;
71         });
73         //result is false
75         var failure, success;
77         Function.attempt(function(){
78                 some.made.up.object = 'something';
79                 success = true;
80         }, function(){
81                 failure = true;
82         });
84         if (success) alert('yey!');
86 ### Notes:
88 This method is an equivalent of *$try* from MooTools 1.2.
92 Function method: extend {#Function:extend}
93 ------------------------------------------
95 Extends a function with a new method or property.
97 ### Syntax:
99         myFunction.extend(key, value);
101         // Or
103         myFunction.extend(object);
105 ### Arguments:
107 1. key - (*string*) The key of the method or property
108 2. value - (*mixed*) The function or property value
112 1. object - (*object*) An object with the key value pairs to add multiple methods or properties
114 ### Returns:
116 * (*function*) The function
118 ### Example:
120         var myFunction = function(){};
121         myFunction.extend('alert', function(text){
122                 alert(text);
123         });
124         myFunction.alert('Hello!'); // alerts Hello!
126         // Using objects
127         myFunction.extend({
128                 alert: function(text){
129                         alert(text);
130                 }
131         });
133 Function method: implement {#Function:implement}
134 ------------------------------------------------
136 Implements a method to the prototype of the function.
138 ### Syntax:
140         myFunction.implement(key, value);
142         // Or
144         myFunction.implement(object);
146 ### Arguments:
148 1. key - (*string*) The method of property name in the prototype
149 2. value - (*mixed*) The function or another value in the prototype
153 1. object - (*object*) An object with key-value pairs to add multiple methods or properties to the function it's prototype.
155 ### Returns:
157 * (*function*) The function
159 ### Example:
161         var myFunction = function(){};
162         myFunction.implement('alert', function(text){
163                 alert(text);
164         });
165         var myInstance = new myFunction();
166         myInstance.alert('Hello!'); // alerts Hello!
168         // Using objects
169         myInstance.implement({
170                 alert: function(text){
171                         alert(text);
172                 }
173         });
175 ### Notes:
177 The difference between *implement* and *extend*, is that implement adds the value to the prototype.
178 So with *implement* each instance of the function will have this method or property while with *extend*
179 the method or property is added to a single instance.
182 Function method: attempt {#Function:attempt}
183 --------------------------------------------
185 Tries to execute a single function. Returns immediately the return value of the function if it does not fail, or null.
187 ### Syntax:
189         var myFunctionResult = myFunction.attempt(args[, bind]);
191 ### Arguments:
193 1. args - (*mixed*) An argument, or array of arguments to run the function with.
194 2. bind - (*object*, optional) The object that the "this" of the function will refer to.
196 ### Returns:
198 * (*mixed*) This Function's return value.
199 * (*null*) `null` if the function fails.
201 ### Examples:
203         var myFunction = function(){
204                 return some.made.up.object;
205         };
206         myFunction.attempt(); // returns 'null'
209         var myFunction = function(val){
210                 return val;
211         };
212         myFunction.attempt(false); // returns 'false'
214 ### See Also:
216 - See [Function.attempt](#Function:Function-attempt) for using more than one functions.
219 Function method: pass {#Function:pass}
220 --------------------------------------
222 Returns a closure with arguments and bind.
224 ### Syntax:
226         var newFunction = myFunction.pass([args[, bind]]);
228 ### Arguments:
230 1. args - (*mixed*, optional) The arguments to pass to the function (must be an array if passing more than one argument).
231 2. bind - (*object*, optional) The object that the "this" of the function will refer to.
233 ### Returns:
235 * (*function*) The function whose arguments are passed when called.
237 ### Example:
239         var myFunction = function(){
240                 var result = 'Passed: ';
241                 for (var i = 0, l = arguments.length; i < l; i++){
242                         result += (arguments[i] + ' ');
243                 }
244                 return result;
245         }
246         var myHello = myFunction.pass('hello');
247         var myItems = myFunction.pass(['peach', 'apple', 'orange']);
249         // Later in the code, the functions can be executed:
250         alert(myHello()); // passes 'hello' to myFunction.
251         alert(myItems()); // passes the array of items to myFunction.
254 ### See Also:
256 [Function:bind][]
259 Function method: bind {#Function:bind}
260 --------------------------------------
262 Changes the scope of `this` within the target function to refer to the bind parameter.
264 ### Syntax:
266         myFunction.bind([bind[, arg1, arg2, ...]]);
268 ### Arguments:
270 1. bind - (*object*, optional) The object that the "this" of the function will refer to.
271 2. arg1, arg2, ... - (*mixed*, optional) The arguments to pass to the function. If the bound function is called with other arguments the arguments are concatenated.
273 ### Returns:
275 * (*function*) The bound function.
277 ### Example:
279         function myFunction(){
280                 // Note that 'this' here refers to window, not an element.
281                 // the function must be bound to the element we want to manipulate.
282                 this.setStyle('color', 'red');
283         };
284         var myBoundFunction = myFunction.bind(myElement);
285         myBoundFunction(); // makes myElement's text red
287         // To show how bind works the following example:
288         var myBoundFunction = myFunction.bind(anyVar);
289         // is roughly equivalent with
290         var myBoundFunction = function(){
291                 return myFunction.call(this);
292         };
294 ### See Also:
296 [Function:pass][]
298 Function method: delay {#Function:delay}
299 ----------------------------------------
301 Delays the execution of a function by a specified duration.
303 ### Syntax:
305         var timeoutID = myFunction.delay(delay[, bind[, args]]);
307 ### Arguments:
309 1. delay - (*number*) The duration to wait (in milliseconds).
310 2. bind  - (*object*, optional) The object that the "this" of the function will refer to.
311 3. args  - (*mixed*, optional) The arguments passed (must be an array if the arguments are greater than one).
313 ### Returns:
315 * (*number*) The JavaScript timeout id (for clearing delays).
317 ### Example:
319         var myFunction = function(){ alert('moo! Element id is: ' + this.id); };
321         //wait 50 milliseconds, then call myFunction and bind myElement to it
322         myFunction.delay(50, myElement); // alerts: 'moo! Element id is: ... '
324         //an anonymous function which waits a second and then alerts
325         (function(){ alert('one second later...'); }).delay(1000);
327         //to stop the delay, clearTimeout can be used like so:
328         var timer = myFunction.delay(50);
329         clearTimeout(timer);
332 ### See Also:
334 - [MDN setTimeout][], [MDN clearTimeout][]
338 Function method: periodical {#Function:periodical}
339 --------------------------------------------------
341 Executes a function in the specified intervals of time. Periodic execution can be stopped using the *clearInterval* function.
343 ### Syntax:
345         var intervalID = myFunction.periodical(period[, bind[, args]]);
347 ### Arguments:
349 1. period - (*number*) The duration of the intervals between executions.
350 2. bind   - (*object*, optional) The object that the "this" of the function will refer to.
351 3. args   - (*mixed*, optional) The arguments passed (must be an array if the arguments are greater than one).
353 ### Returns:
355 * (*number*) The Interval id (for clearing a periodical).
357 ### Example:
359         var Site = { counter: 0 };
360         var addCount = function(){ this.counter++; };
361         addCount.periodical(1000, Site); //adds the number of seconds at the Site.
363         // the interval can be stopped using the clearInterval function
364         var timer = myFunction.periodical(1000);
365         clearInterval(timer);
367 ### See Also:
369 - [MDN setInterval][], [MDN clearInterval][]
372 Deprecated Functions {#Deprecated-Functions}
373 ============================================
375 Function method: create {#Deprecated-Functions:create}
376 ------------------------------------------------------
378 This function has been deprecated.
380 Function method: bindWithEvent {#Deprecated-Functions:bindWithEvent}
381 --------------------------------------------------------------------
383 This function has been deprecated.
385 ### Example how you could replace this method:
387         myElement.addEvent('click', function(e){
388                 myFunction.call(bind, e);
389         });
391 Function method: run {#Deprecated-Functions:run}
392 ------------------------------------------------
394 This function has been deprecated.
396 ### Replacement example
398         fn.apply(thisArg, arguments); // Old API: fn.run(arguments, thisArg);
401 [Function:bind]: /core/Types/Function/#Function:bind
402 [Function:pass]: /core/Types/Function/#Function:pass
403 [Element:addEvent]: /core/Element/Element.Event/#Element:addEvent
404 [MDN Function]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function
405 [MDN setInterval]: https://developer.mozilla.org/en/DOM/window.setInterval
406 [MDN setTimeout]: https://developer.mozilla.org/en/DOM/window.setTimeout
407 [MDN clearInterval]: https://developer.mozilla.org/en/DOM/window.clearInterval
408 [MDN clearTimeout]: https://developer.mozilla.org/en/DOM/window.clearTimeout