Search code examples
javascriptjqueryjquery-uijquery-callback

Some value to callback function


So, I have this simple code

$('#info_name'+index).show("slide", {direction: "right"}, 1000, function(){
    $('#info_info'+index).show('slide',{direction: "up"}, 1000);
});

The i is declared upper as just a variable var i=0, but in callback, function I can't see it...


Solution

  • There is a scope issue with i. Since i is declared in the outer scope, all callbacks will reference the same i, meaning, if i is changed, all callbacks' references to i will also be changed.

    What you can do is to create a function to generate the callback, since a new scope is created in that case, the value of i will be preserved.

    Based on the original question, I simplified the code a little bit. You've since edited it, and I can't find the callback anymore... but hope this might help ya

    var getCallback = function(index) {
        return function(){
            // You can see how this index is being captured correctly in Javascript console
            console.log(index);
            $('#name' + index).show('slide',{direction: "up"}, 1000)
        };
    };
    
    for (var i = 0; i < 3; ++i) {
        $('#name'+i).show("slide", {direction: "right"}, 1000, getCallback(i));
    }
    

    JSFiddle: http://jsfiddle.net/vd9Mj/

    UPDATE:

    Where's your callback...? It seems you've removed it from the question.

    var i=-1;
    
    var doStuff = function(index) {
        $('.third').append('<div class="showinfo"><h3 id="info_name'+i+'" class="info_name">'+contact_name[index]+'</h3><span class="info_info" id="info_info'+index+'"><strong>'+contact_information[0][0]+'</strong>: '+contact_number[index]+'</span></div>');
        $('#info_name'+index).show("slide", {direction: "right"}, 1000);
        $('#info_info'+index).delay(1000).show('slide',{direction: "up"}, 1000, function() {
           // Insert code for callback.
        });
    };
    
    $.each(contact_status, function(key, value){
        i++;
        if(value == info_id){
            doStuff(i);
        }
    });
    ​