Boso
Boso

Reputation: 87

Why is a callback function being converted to a JQuery.Event

I have the following code that should display a DIV then trigger a callback that shows a second DIV. For some reason whenever I execute it, the the confirmPayment function never gets executed. When I look at it in a debugger it says the confirmPayment callback is a JQuery.Event object and not a function. This doesn't make sense, any idea why this is occuring?

$(function(){
var socket = io.connect('http://localhost:3000');
var confirmPayment = function(){
    socket.on('paid', function (data) {
        function confirmEmitter(callback){
            $('#confirmed').html(JSON.stringify(data)).show("slow");
            callback();
        };

        confirmEmitter(function(){
            socket.emit('confirmed', { my: 'Showing result' });
        });
    });
};

var sendPayment = function(confirmPayment){
    $('#submitted').html(d.method + '<br>' + d.note).show("slow");

            /////WHY IS THIS AN OBJECT?/////
            confirmPayment();
            /////WHY IS THIS AN OBJECT?/////
};
$('#doIt').click(sendPayment);

 });

Upvotes: 0

Views: 50

Answers (2)

gitaarik
gitaarik

Reputation: 46300

You cannot pass parameters when you create the function. So the parameter confirmPayment on the function sendPayment is just the first parameter of this function, and when calling the function, the first argument to the function will be stored in confirmPayment.

Now this function get's called by jQuery's click event, and jQuery's click event passes an eventObject as first parameter.

If you want to call the confirmPayment function from within sendPayment, just call it like confirmPayment(), but make sure you have no other variables defined with that name, because then you'll try to call that new variable.

So just remove the first parameter confirmPayment on sendPayment.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

sendPayment is registered as a event callback, so when jquery calls sendPayment it will pass the event as the first parameter.

In your case since confirmPayment is a closure function within the same scope you can just call confirmPayment() from sendPayment

var sendPayment = function(e){
    $('#submitted').html(d.method + '<br>' + d.note).show("slow");

            /////WHY IS THIS AN OBJECT?/////
            confirmPayment();
            /////WHY IS THIS AN OBJECT?/////
};

Upvotes: 1

Related Questions