Replaced $clear (deprecated) with clearInterval
[mootools.git] / Docs / Types / Function.md
blob4e683a0680d3d5c6a22bd342ea788ed092a4fedc
1 Type: Function {#Function}
2 ==========================
4 Function Methods.
6 ### See Also:
8 - [MDC Function][]
12 Function: Function.from {#Function:Function-from}
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.from(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.from(42);
32         alert(fn());    // alerts '42'
34         var fn2 = Function.from(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.from();              // equivalent to var fn1 = $empty();
42         var fn2 = Function.from(foo);   // equivalent to var fn2 = $lambda(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 Add methods to a function
97 ### Syntax:
99         myFunction.extend(key,value);
101 ### Arguments:
103 1. key - (*string*) The key of the prototype
104 2. value - (*mixed*) The function or another value of the prototype
106 ### Example:
108         var myFunction = function(){};
109         myFunction.extend('alert', function(text){
110                 alert(text);
111         });
112         myFunction.alert('Hello!'); // alerts Hello!
115 Function method: implement {#Function:implement}
116 ---------------------------------------
118 Add methods to the prototype
120 ### Syntax:
122         myFunction.implement(key,value);
124 ### Arguments:
126 1. key - (*string*) The key of the prototype
127 2. value - (*mixed*) The function or another value of the prototype
129 ### Example:
131         var myFunction = function(){};
132         myFunction.implement('alert', function(text){
133                 alert(text);
134         });
135         var myInstance = new myFunction();
136         myInstance.alert('Hello!'); // alerts Hello!
138 ### Notes:
140 The difference between *implement* and *extend*, is that implement adds the value to the prototype.
141 So with *implement* each instance of the function will have this method or property while with *extend*
142 the method or property is added to a single instance.
145 Function method: attempt {#Function:attempt}
146 ---------------------------
148 Tries to execute a single function. Returns immediately the return value of the function if it does not fail, or null.
150 ### Syntax:
152         var myFunctionResult = myFunction.attempt(args[, bind]);
154 ### Arguments:
156 1. args - (*mixed*) An argument, or array of arguments to run the function with.
157 2. bind - (*object*, optional) The object that the "this" of the function will refer to.
159 ### Returns:
161 * (*mixed*) This Function's return value.
162 * (*null*) `null` if the function fails.
164 ### Examples:
166         var myFunction = function(){
167                 return some.made.up.object;
168         };
169         myFunction.attempt(); // returns 'null'
172         var myFunction = function(val){
173                 return val;
174         };
175         myFunction.attempt(false); // returns 'false'
177 ### See Also:
179 - See [Function.attempt](#Function:Function-attempt) for using more than one functions.
182 Function method: pass {#Function:pass}
183 -----------------------------
185 Returns a closure with arguments and bind.
187 ### Syntax:
189         var newFunction = myFunction.pass([args[, bind]]);
191 ### Arguments:
193 1. args - (*mixed*, optional) The arguments to pass to the function (must be an array if passing more than one argument).
194 2. bind - (*object*, optional) The object that the "this" of the function will refer to.
196 ### Returns:
198 * (*function*) The function whose arguments are passed when called.
200 ### Example:
202         var myFunction = function(){
203                 var result = 'Passed: ';
204                 for (var i = 0, l = arguments.length; i < l; i++){
205                         result += (arguments[i] + ' ');
206                 }
207                 return result;
208         }
209         var myHello = myFunction.pass('hello');
210         var myItems = myFunction.pass(['peach', 'apple', 'orange']);
212         //Later in the code, the functions can be executed:
213         alert(myHello()); // passes 'hello' to myFunction.
214         alert(myItems()); // passes the array of items to myFunction.
218 Function method: bind {#Function:bind}
219 -----------------------------
221 Changes the scope of `this` within the target function to refer to the bind parameter.
223 ### Syntax:
225         myFunction.bind([bind[, arg1, arg2, ...]]);
227 ### Arguments:
229 1. bind - (*object*, optional) The object that the "this" of the function will refer to.
230 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.
232 ### Returns:
234 * (*function*) The bound function.
236 ### Example:
238         function myFunction(){
239                 //Note that 'this' here refers to window, not an element.
240                 // the function must be bound to the element we want to manipulate.
241                 this.setStyle('color', 'red');
242         };
243         var myBoundFunction = myFunction.bind(myElement);
244         myBoundFunction(); // makes myElement's text red
247 Function method: delay {#Function:delay}
248 -------------------------------
250 Delays the execution of a function by a specified duration.
252 ### Syntax:
254         var timeoutID = myFunction.delay(delay[, bind[, args]]);
256 ### Arguments:
258 1. delay - (*number*) The duration to wait (in milliseconds).
259 2. bind  - (*object*, optional) The object that the "this" of the function will refer to.
260 3. args  - (*mixed*, optional) The arguments passed (must be an array if the arguments are greater than one).
262 ### Returns:
264 * (*number*) The JavaScript timeout id (for clearing delays).
266 ### Example:
268         var myFunction = function(){ alert('moo! Element id is: ' + this.id); };
270         //wait 50 milliseconds, then call myFunction and bind myElement to it
271         myFunction.delay(50, myElement); // alerts: 'moo! Element id is: ... '
273         //an anonymous function which waits a second and then alerts
274         (function(){ alert('one second later...'); }).delay(1000);
276         //to stop the delay, clearTimeout can be used like so:
277         var timer = myFunction.delay(50);
278         clearTimeout(timer);
281 ### See Also:
283 - [MDC setTimeout][], [MDC clearTimeout][]
287 Function method: periodical {#Function:periodical}
288 -----------------------------------------
290 Executes a function in the specified intervals of time. Periodic execution can be stopped using the *clearInterval* function.
292 ### Syntax:
294         var intervalID = myFunction.periodical(period[, bind[, args]]);
296 ### Arguments:
298 1. period - (*number*) The duration of the intervals between executions.
299 2. bind   - (*object*, optional) The object that the "this" of the function will refer to.
300 3. args   - (*mixed*, optional) The arguments passed (must be an array if the arguments are greater than one).
302 ### Returns:
304 * (*number*) The Interval id (for clearing a periodical).
306 ### Example:
308         var Site = { counter: 0 };
309         var addCount = function(){ this.counter++; };
310         addCount.periodical(1000, Site); //adds the number of seconds at the Site.
312         // the interval can be stopped using the clearInterval function
313         var timer = myFunction.periodical(1000);
314         clearInterval(timer);
316 ### See Also:
318 - [MDC setInterval][], [MDC clearInterval][]
321 Deprecated Functions {#Deprecated-Functions}
322 ============================================
324 Function method: create {#Deprecated-Functions:create}
325 ------------------------------------------------------
327 This function has been deprecated.
329 Function method: bindWithEvent {#Deprecated-Functions:bindWithEvent}
330 --------------------------------------------------------------------
332 This function has been deprecated.
334 ### Example how you could replace this method:
336         myElement.addEvent('click', function(e){
337                 myFunction.bind(bind, [e]);
338         });
340 Function method: run {#Deprecated-Functions:run}
341 ------------------------------------------------
343 This function has been deprecated.
345 ### Replacement example
347         fn.apply(thisArg, arguments); // Old API: fn.run(arguments, thisArg);
350 [options]: #Function:create:options
351 [Element:addEvent]: /core/Element/Element.Event/#Element:addEvent
352 [MDC Function]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function
353 [MDC setInterval]: https://developer.mozilla.org/en/DOM/window.setInterval
354 [MDC setTimeout]: https://developer.mozilla.org/en/DOM/window.setTimeout
355 [MDC clearInterval]: https://developer.mozilla.org/en/DOM/window.clearInterval
356 [MDC clearTimeout]: https://developer.mozilla.org/en/DOM/window.clearTimeout
357 [Function:delay]: /core/Types/Function/#delay
358 [Function:periodical]: /core/Types/Function/#periodical