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

                }); 
            }
        }

    });
3
  • It shouldn't be. Maybe the error is that tweets[i] is undefined, which is likely because you didn't make a closure. Commented May 10, 2013 at 16:11
  • What do you mean by a closure? Commented May 10, 2013 at 16:11
  • possible duplicate of Javascript closure inside loops - simple practical example Commented May 10, 2013 at 16:14

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.