3

My original (working) code looks like:

jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(function () {
        $(this).html("");
    });
    $('[id="errorMessages"]').ajaxError(function (e, jqxhr, settings, exception) {
        //...
    });
});

When I am trying to replace the anonymous functions into a named function calls like: (I am doing a POC for some requirement, which expects such implementation.)

function fs() {
        $(this).html("");
}
function fe(e, jqxhr, settings, exception) {
        //...
}
jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(fs());
    $('[id="errorMessages"]').ajaxError(fe(e, jqxhr, settings, exception));
});

I am getting an error stating the parameter 'e' is undefined. But the functions without parameters seems working fine.

I am wondering how the anonymous functions could receive the parameters, while the same not available when calling an external function.

Is there a way to convert these parameterized anonymous functions into regular function calls.

2
  • try replacing e by "" when you are calling it Commented Sep 12, 2013 at 9:50
  • 2
    $('[id="errorMessages"]').ajaxStart(fs); not $('[id="errorMessages"]').ajaxStart(fs()); Commented Sep 12, 2013 at 9:51

1 Answer 1

6

You are assigning the functions to the handlers incorrectly, try this:

jQuery().ready(function ($) {
    $('[id="errorMessages"]').ajaxStart(fs);
    $('[id="errorMessages"]').ajaxError(fe);
});

Note that passing the name of the function without brackets means you are giving the reference of that function which should be used when the event occurs.

Your current code will call the function when the event is attached (hence why you're getting 'e' is undefined) and assign the result of the function to the event handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.