2012-11-18 49 views
4

動畫我有follwing代碼,我是從兩個環路增加內部隊列效應:回調時創建動態完成

tablaActual = ({ 
    1111: { 
     titulo: "Nuevo Video 1", 
     usuario: "RadioBot", 
     alta: "1353182478" 
    }, 
    2243: { 
     titulo: "Old Boy Fashion", 
     usuario: "RadioBot", 
     alta: "1353182479" 
    }, 
    3432: { 
     titulo: "Britney spears", 
     usuario: "RadioBot", 
     alta: "1353182825" 
    } 
}); 

tablaNueva = ({ 
    1111: { 
     titulo: "Nuevo Video 1", 
     usuario: "RadioBot", 
     alta: "1353182478" 
    }, 
    1112: { 
     titulo: "Nuevo video 2", 
     usuario: "RadioBot", 
     alta: "1353182477" 
    }, 
    1113: { 
     titulo: "Nuevo video 3", 
     usuario: "RadioBot", 
     alta: "1353182476" 
    } 
}); 


$("button").bind("click", function() { 

    var body = $('body'); 

    retardation = 500; 
    i = 1; 

    // we delete the old ones that doesnt match in the new table 
    $.each(tablaActual, function(index) { 
     if (!tablaNueva[index]) { 
      delay = i * retardation; 

      $('#lista #id' + index).delay(delay).slideUp("normal", function() { 
       $(this).remove(); 
      }).queue("cola1"); 

      delete tablaActual[index]; 
      i++; 
     } 
    }); 

    // we add the new ones that doesnt match in the old table 
    $.each(tablaNueva, function(index, vars) { 
     if (!tablaActual[index]) { 

      delay = i * retardation; 
      $('<tr id="id' + index + '"><td class="cancion"><h3>' + vars.titulo + '</h3></td><td class="autor">' + vars.usuario + '<span>' + vars.alta + '</span></td></tr>').appendTo('#lista').hide().delay(delay).show('slow').queue("cola2"); 


      tablaActual[index] = vars; 
      i++; 


     } 
    }); 

    $("tr:animated").promise().done(function() { 

     alert("done"); 
    }); 


}); 

jsFiddle

當所有的TR動畫完成,它應該觸發警報,但我認爲我做錯了,因爲只要點擊運行按鈕,警報就會彈出。

我該怎麼做?

回答

2

我會使用jQuery.Deferred()使其工作。通過這樣做,您可以排列許多延遲對象,一旦相應的項目動畫完成,就會解析這些對象。

總之,創建一個延期對象數組,並使用有點奇怪的構造jQuery.when.apply(...).done(function() { ... })等待它們。請參閱this JSFiddle

0

如果所有的動畫已經完成你可以在show功能和測試的回調將您的警報(完成回調):http://jsfiddle.net/dSGWx/12/

var totalmacth=0; 
var loop=0; 
// los que se tienen que añadir 
$.each(tablaNueva, function(index, vars) { 
    if (!tablaActual[index]) { 
    totalmacth++; 

    delay = i * retardation; 
    $('<tr id="id' + index + '"><td class="cancion"><h3>' + vars.titulo + '</h3></td><td class="autor">' + vars.usuario + '<span>' + vars.alta + '</span></td></tr>').appendTo('#lista').hide().delay(delay) 
     .show('slow',function(){ 
       loop++; 
       console.log(loop + ' ' + totalmacth)     
       if(loop === totalmacth) 
        alert("done"); 

      }); 
    tablaActual[index] = vars; 
    i++; 
    }  
}); 
+0

我覺得mzedeler方式是更好的,你同意這種說法? – Aleix

+0

我同意。我的答案是解決你的問題的簡單方法,而@ mzedeler的答案是最好的。 – sdespont