Search code examples
javascriptajaxcallbackevaljquery-callback

Generating an array of distinct callback functions in Javascript


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.


Solution

  • 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.