user2359318
user2359318

Reputation: 83

jquery callback undefined array

I am getting an error saying that json array "tweets" is undefined in the animate callback...

    $.getJSON('php/engine.php', function(tweets){

        if (tweets.length != 0) {

            for (var i = 0; i < tweets.length; i++) {

                $('#1').animate({opacity: 0}, 2000, function() {

                    $(this).css('background-color', 'red').html(

                        '<p><span class="profile_image">' + tweets[i]['profile_image_url'] + '</span>' +
                        '<span class="name">' + tweets[i]['name'] + '</span>' + 
                        '<span class="mention">' + tweets[i]['screen_name'] + '</span></p>' +
                        '<p><span class="text">' + tweets[i]['text'] + '</span></p>').animate({opacity: 1}, 2000);

                }); 
            }
        }

    });

Upvotes: 0

Views: 137

Answers (1)

Halcyon
Halcyon

Reputation: 57709

You've got a closure problem, here's how to remedy it:

for (var i = 0; i < tweets.length; i++) {
    (function (real_i) {
        $('#1').animate({opacity: 0}, 2000, function() {
            console.log(tweets[real_i]);
        });
    }(i)); // <-- immediate invocation
}

The animate-callback is getting called much later, by then the value of i is tweets.length and tweets[tweets.length] is undefined.

Another, more simple solution is to use a map-function instead of for, the closure then is free.

function map(array, callback) {
    for (var i = 0; i < array.length; i += 1) {
        callback(array[i], i);
    }
}

map(tweets, function (value, index) { // value and index are already 'closed' to this scope
    console.log(value);
});

Upvotes: 2

Related Questions