2013-08-16 5 views
0

У меня есть функция, которая работает так, как я ее тоже хочу, только она выглядит действительно беспорядочной и раздутой, и поэтому мне интересно, есть ли лучший способ кодировать ниже?Оптимизация обратных вызовов jQuery

function careerFlyIn(){ 

    var distance = $('.row').offset().top, 
     $window = $(window); 
    var distance = distance - 200; 
    var flyInR = $('.path-description'); 
    var flyInL = $('.path-title'); 

    $window.scroll(function() { 
     if ($window.scrollTop() >= distance) { 
      $('.career-path .row:first-child').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function() { 
       $('.career-path .row:nth-child(2)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function() { 
        $('.career-path .row:nth-child(3)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function() { 
         $('.career-path .row:nth-child(4)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function() { 
          $('.career-path .row:nth-child(5)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function() { }); 
         }); 
        }); 
       });    
      }) 
      $('.career-path .row:first-child').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function() { 
       $('.career-path .row:nth-child(2)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function() { 
        $('.career-path .row:nth-child(3)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function() { 
         $('.career-path .row:nth-child(4)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function() { 
          $('.career-path .row:nth-child(5)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function() { }); 
         }); 
        }); 
       });    
      }) 
     } 
    }); 

}; 

ответ

2

Создайте список элементов для анимации и использования рекурсии async в списке.

function animate(elements, callback) 
{ 
    if (elements.length){ 
     elements.eq(0).find(flyInR).animate({ 'right' : '0px' }, 400, 'easeOutBounce'); 
     elements.eq(0).find(flyInL).animate({ 'left' : '0px' }, 400, 'easeOutBounce', function(){ 
      // Do the remainder of the list (after first item) 
      animate(elements.slice(1), callback); 
     }); 
    } 
    else { 
     // All done, call the final callback 
     callback(); 
    } 
} 

animate($('.career-path .row'), function() 
{ 
    // do something when all items have finished animating 
}); 

Вы можете применить этот шаблон к любому набору аналогичных операций async. В этом примере левая и правая анимации запускаются параллельно, но только одно запускает следующее событие (в данном случае - левое).

+0

Почему downvote? Это работает и является полезной техникой для многих асинхронных проблем. –

1

Помогает ли это?

$window.scroll(function() { 
    if ($window.scrollTop() >= distance) { 

    $('.career-path .row').each(function(i) { 
     $(this).find(flyInL).delay(400*i) 
      .animate({ 'left' : '0px' } ,400, 'easeOutBounce'); 

     $(this).find(flyInR).delay(400*i) 
      .animate({ 'right' : '0px' } ,400, 'easeOutBounce'); 
    }); 
    } 
}); 

Использование JQuery .delay() метод, Sets a timer to delay execution of subsequent items in the queue.

+2

Используя метод '.delay()', анимации происходят друг с другом. –

+0

Правда. Я снимаю свой комментарий :) –

0

Try

function animate($rows, idx, selector, animate) { 
    $rows.eq(idx).find(selector).animate(animate, 400, 'easeOutBounce', function() { 
     if (idx < $rows.length - 1) { 
      animate($rows, idx + 1, selector, animate) 
     } 
    }); 
} 

var $rows = $('.career-path .row'); 
animate($rows, 0, flyInL, { 
    'left' : '0px' 
}) 
animate($rows, 0, flyInR, { 
    'right' : '0px' 
}) 

Примечание: Не тестировалось

Смежные вопросы