0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.