0

I'm trying to use a variable value in a callback function, but am unable to get the original value of the variable when written into the function.

for (i=0; i<2; i++) {
    if ($.type(picker[i]) == "object") {
        var id = picker[i].$root[0].id;
        picker[i].on({
            set: function() {
                alert("#" + id + " .picker__holder");
            },
        });
        // other code..
    }
}

This code is supposed to go throught the picker object twice, where the id value is first "datepicker" and on the second run "datepicker--2" but when the callback is called the id is always the second value "datepicker--2" where for the picker[0].on() callback i'd need it to be the first one ("datepicker").

I assume this is because the value of the variable is read when the callback code is executed, and by that time it has the last value.

What would be a reasonable workaround for this?

Best,

Alari

Alari Truuts
  • 310
  • 4
  • 12

1 Answers1

1

You need to refactor the inner asynch call into a function.

for (i=0; i<2; i++) {
    if ($.type(picker[i]) == "object") {
        var id = picker[i].$root[0].id;
        // other code..
        asynhCall(picker, i, id);
    }
}
function asynhCall(picker, i, id)
{
        picker[i].on({
            set: function() {
                alert("#" + id + " .picker__holder");
            },
        });
}

This is because by the time asynch-callback handler was executed, only id will have only the last value would be used (since because of event-loop model).

gurvinder372
  • 66,980
  • 10
  • 72
  • 94