0

我有以下代码应该显示一个 DIV 然后触发一个显示第二个 DIV 的回调。出于某种原因,每当我执行它时,该confirmPayment函数永远不会被执行。当我在调试器中查看它时,它说confirmPayment回调是一个JQuery.Event对象而不是一个函数。这没有意义,知道为什么会这样吗?

$(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);

 });
4

2 回答 2

1

sendPayment注册为事件回调,所以当 jquery 调用时sendPayment,它会将事件作为第一个参数传递。

在您的情况下,因为confirmPayment是同一范围内的闭包函数,您可以从中confirmPayment()调用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?/////
};
于 2013-04-29T11:43:17.573 回答
1

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.

于 2013-04-29T11:51:46.233 回答