The Angry Saxon
The Angry Saxon

Reputation: 792

jQuery passing function for callback but make use of return value

Okay lets begin,

I have created an ajax namespace in javascript that just made it easier to remember what values needed to be inserted in-order to get it to work.

(function (ns) {
    ns.type = "POST";
    ns.url = "/";
    ns.data = {};
    ns.success = function() {};

    ns.send = function() {
        $.ajax({
            type: ns.type,
            url: ns.url,
            data: ns.data,
            success: ns.success()
        });
    }

}(fps.ajax));

to make use of it I do the following

var ajax = fps.ajax;
ajax.url = "/credit/getBalance";
ajax.type = "GET";
ajax.success = function (e) {
    navCredits.text(navCredits.text().f(e));
};
ajax.send();

now the problem I'm having is my success function.

I pass it a varible that I want my ajax function to use as it's return data but it's not happening in that way.

My understanding of this is that it's (e) not declaired where the success function is being set, hence why I'll get an undefined value.

My question is, is there a way to pass a function with a "parameter" that the function should use for it's own functions value?

I don't feel like I'm explaining very well but hopefully there's enough code there to help you understand what I'm trying to achieve.

Kind regards

Upvotes: 0

Views: 118

Answers (1)

Daved
Daved

Reputation: 2082

You're executing your success function instead of assigning it as the handler. Remove the () off the "success:ns.success()" line.

ns.send = function() {
    $.ajax({
        type: ns.type,
        url: ns.url,
        data: ns.data,
        success: ns.success  // you don't want to execute
    });
}

When you put the "()" after a function reference, it will execute it at that moment. In your case, it's executing an empty function, as defined a few lines up. Your success function with the arguments for the event is declared fine, but never being used.

When you remove the "()", it assigns the function object to the property. When you add the "()" it executes the function at that moment and assigns the return value to the property. And when the jQuery "ajax" call is completed successfully, the success function is executed on that object, so they handle the adding of the "()" at that time. ;)

Upvotes: 2

Related Questions