How do I reference an anonymous JavaScript function?
I am trying to call a page method using jQuery's "attached" event function in which I like to use a closure to make the local event local like below, but the page method calls declare multiple "error" functions and I would like to use one function to all of them. If in the code below I was handling the error and had no time to keep up, how could I use my single anonymous handler for all three error functions?
$(":button").click(function () {
var button = this;
PageMethods.DoIt(
function (a, b, c) {
alert(button);
});
});
This example executes an anonymous function for the success callback. There is only one of them. If I was going through the error callback, how could I use the (e, c, t) function for all 3 error callbacks?
ADDED: What I would like to do here makes an AJAX call whenever the user clicks a toggle button (checkbox), but for better performance I want to immediately toggle the state of the button and only "unbind" it if the AJAX call fails.
Now, in the client side event handler click()
, I would like to use anonymous functions inside the scope of click()' so that the functions have access to the
this event argument, but I don't want to 'declare' three functions for the
onTimeout ,
onError of the , and 'onAbort
arguments of the PageMethods.MyFunction function. if I declare a named function outside of a click handler, it no longer has access to the 'this' parameter of the event handler click()
.
a source to share
If your goal is to keep this function out of the global scope, then use the module template :
(function() {
function asplode() {
alert('Your head asplode.');
}
$('body').click(asplode);
})();
a source to share
You must assign the anonymous function to the variable with var
(always use var
, otherwise the variable will get global scope, which can lead to unexpected results (for example, never declare the variable i
globally)). This is the only way to reference it:
var myFunction = function (a, b, c) {
/* tum de dum */
}; // don't forget this semicolon
Then you can use this function in different places:
$(":button").click(myFunction);
/* don't put braces after the function name when referencing it,
else it will be called immediately */
More information on function expressions and function declarations can be found in the article Named Function Expressions, Demystified .
a source to share