ctrl-alt-delor
ctrl-alt-delor

Reputation: 7745

javascript anonymous function with access to variable in creator

I need to access the i variable from the loop, in the success function. How do I do that?, can I pass it in to the function?

function save(){
    var mods=model.things;
    for (i in mods) {
        var mod= mods[i];
        $.ajax({
            url: "duck"
            type: "put",
            data: JSON.stringify(mod),
            success: function(responce_json) {
                var j=i;   
            }
        });
    }
}

Upvotes: 2

Views: 94

Answers (2)

Matt Burland
Matt Burland

Reputation: 45155

One way:

        success: (function(i) { return function(responce_json) {
            var j=i;   
        }})(i)

This uses an Immediately Invoked Function Expression (IIFE) to create a closure that will capture the current value of i.

Incidently, for...in is considered bad practice by a lot of JavaScript programmers, but if you need to use it, you should probably at least include a check for hasOwnProperty

Upvotes: 3

JaredPar
JaredPar

Reputation: 755131

Create another function that takes i as a parameter thus creating a local copy for each iteration

var f = function(i) { 
    var mod= mods[i];
    $.ajax({
        url: "duck"
        type: "put",
        data: JSON.stringify(mod),
        success: function(responce_json) {
            var j=i;   
        }
    });
}
for (iter in mods) {
    f(iter);
}

Upvotes: 1

Related Questions