0

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);

                }); 
            }
        }

    });
user2359318
  • 83
  • 1
  • 1
  • 5
  • It shouldn't be. Maybe the error is that `tweets[i]` is undefined, which is likely because you didn't make a closure. – Halcyon May 10 '13 at 16:11
  • What do you mean by a closure? – user2359318 May 10 '13 at 16:11
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – bfavaretto May 10 '13 at 16:14

1 Answers1

2

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);
});
Halcyon
  • 57,230
  • 10
  • 89
  • 128