Yet another javascript function scope question – Education Career Blog

In this code, the ident and data variables are correct in the callback, but I don’t know how to pass in the right i for each loop iteration. I’ve tried reading up on functions and tried like 10 things, but alas, I must seek the wisdom of the stack.

function callback()
{
    $(ident).html( data.fieldsi.value );
    $(ident).fadeTo('slow',1);
}

for(i=0;i<data.fields.length;i++)
{
    ident='#'+data.rID+'_'+data.fieldsi.field;
    $(ident).fadeTo('slow',0,callback);
}

,

Change your “callback” function:

function callback(i) {
  return function() {
    $(ident).html( data.fieldsi.value );
    $(ident).fadeTo('slow',1);
  };
}

Then in your loop:

$(ident).fadeTo('slow',0,callback(i));

This “callback” implementation returns the function that you’ll pass to “fadeTo()”.

,

One way would be to declare the callback function within the for loop.

,

My original answer was incorrect. Thanks to @Pointy for the heads-up.

This is similar to @Pointy’s answer, but has different placement for the closure.

function callback(k) {
     $( this ).html( data.fieldsk.value );
     $( this ).fadeTo('slow',1);
}

for(i=0;i<data.fields.length;i++) {
    (function(j) {
             ident='#'+data.rID+'_'+data.fieldsj.field;
             $(ident).fadeTo('slow',0, function() { callback.call( this, j) });
    })(i);
}

,

You can use an anonymous function instead of the pointer to callback, so that you can pass in i to callback.

function callback(i, elem)
{
    $(elem).html( data.fieldsi.value );
    $(elem).fadeTo('slow',1);
}

for(i=0;i<data.fields.length;i++)
{
    var ident='#'+data.rID+'_'+data.fieldsi.field;
    $(ident).fadeTo('slow',0,function() { callback(i, this); });
}

Rather than making ident a global variable, it would be best to declare it (making it constrained to the current function’s scope), and then use this in the callback to reference that element.

If you’re not using callback anywhere else, it may make sense to just put its implementation inside of the anonymous function, rather than defining it separately and calling out to it:

for(i=0;i<data.fields.length;i++)
{
    ident='#'+data.rID+'_'+data.fieldsi.field;
    $(ident).fadeTo('slow',0,function() { 
        $(ident).html( data.fieldsi.value );
        $(ident).fadeTo('slow',1);
    });
}

The above example with the inline anonymous function doesn’t work, because the reference to i is shared between the callbacks.

Leave a Comment