开发者

Generating an array of distinct callback functions in Javascript

开发者 https://www.devze.com 2023-03-24 00:16 出处:网络
I\'m trying to generate an array of callback functions for use in a jQuery UI dialog Given the following code:

I'm trying to generate an array of callback functions for use in a jQuery UI dialog

Given the following code:

for(var x in methods)
{

  buttons[x] = function() {

            var method = methods[x];

            var data = $('#dialog_'+model+' form').serialize();
            data += '&form='+model;
            $.post(
                    $('#dialog_'+model+' form').attr('action')+'method/'+method+'/',
                    data,
                    function(r) {
                            handleFormReturn(r);   
                 开发者_运维技巧   },
                    'json'
            );
  };

}

When called, the function will obviously use the last known value of the variable x and not the one that I need. How can I avoid this problem without having to resort to using eval() ?

Maybe I'm going about this all wrong but as far as I know it's not possible to pass a parameter to the callback.


You need to create a new variable scope during each pass in the for loop. This can only be done by invoking a function.

function createButton(x) {
    buttons[x] = function () {
        var method = methods[x];
        var data = $('#dialog_' + model + ' form').serialize();
        data += '&form=' + model;
        $.post(
        $('#dialog_' + model + ' form').attr('action') + 'method/' + method + '/', data, function (r) {
            handleFormReturn(r);
        }, 'json');
    };
}
for (var x in methods) {
    createButton(x);
}

Now the value of x that the buttons[x] function refers to will be the one that was passed to createButton.


An immediate function version of patrick dw's solution:

for (var x in methods) {
    buttons[x] = (function (x) {
        return function () {
            /* ... x is local for this function ... */
        };
     })(x);
}


You need to create a closure for each element in methods array:

for(var x in methods) {

    buttons[x] = (function(x) {

        var method = methods[x];

        return function () {
            var data = $('#dialog_'+model+' form').serialize();
            data += '&form='+model;
            $.post(
                $('#dialog_'+model+' form').attr('action')+'method/'+method+'/',
                data,
                function(r) {
                        handleFormReturn(r);   
                },
                'json'
            );
        };
    })(x);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消