簡體   English   中英

何時使用jQuery動畫承諾而不是回調?

[英]When to use jQuery animation promises instead of the callback?

我有以下查詢。 何時使用此:

$('#box').hide(2000).promise().done(function(){
     $('#output').text('Box is hidden');
});

而不是這個:

$('#box').hide(2000,function(){
     $('#output').text('Box is hidden');
});

.promise()方法與jQuery動畫一起使用有哪些有用的場景?

謝謝

如果您只是為一個項目制作動畫,則沒有理由在直接回調中使用承諾。 在這種特殊情況下,當您嘗試協調多個不同的異步操作(承諾通常最有用的地方)時,promises會更有用。

假設你有一大堆你隱藏的物品,當你完成所有這些時你想要一個回調。 然后,這將完成:

$('.items, .boxes').hide(2000).promise().then(function(){
     $('#output').text('All hidden');
});

或者,假設您想知道何時完成了多個不同的動畫,因此您需要協調多個動作。 Promise有內置的功能,更多的工作是手工編碼而沒有承諾:

var p1 = $('.items, .boxes').hide(2000).promise();
var p2 = $('.sliders').slideUp(2500).promise();
var p3 = $('.openers').slideDown(1500).promise();
$.when(p1, p2, p3).then(function() {
    // all are done here
});

如果你想手持沒有承諾的代碼,那么你將不得不維護一個計數器,並在每個單獨的回調中,檢查計數器,看看它們是否全部完成。 這是更多的代碼。 現在,如果你有處理錯誤或鏈接到其上的多個其他操作,任何沒有回調或沒有一些異步支持庫的選項很快就會成為手動代碼的真正痛苦。 這就是為什么承諾被發明的原因。

或者,甚至超出動畫范圍,想象你想要協調一個動畫和一個ajax調用(你不知道需要多長時間):

var p1 = $('.items, .boxes').hide(2000).promise();
var p2 = $.ajax(...);
$.when(p1, p2).then(function() {
    // both are done here
});

這是一個關於通知差異的演示。 如果您按“重置”,然后按“回撥”,您將看到您收到5個完成通知。 如果您按“重置”然后按“承諾”,您將看到完成后會收到1個完成通知。

 // configure logging log.id = "results"; $("#runPromises").click(function() { $('.items, .boxes').hide(2000).promise().then(function(){ log("got done notification") }); }); $("#runCallbacks").click(function() { $('.items, .boxes').hide(2000, function(){ log("got done notification") }); }); $("#reset").click(function() { $(".items, .boxes").show(); $("#results").empty(); }); 
 .items { height: 50px; width: 200px; background-color: red; margin-top: 10px; } .boxes { height: 30px; width: 30px; background-color: blue; margin-top: 10px; } #results { margin-top: 30px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://files.the-friend-family.com/log.js"></script> <button id="runCallbacks">Callbacks</button> <button id="runPromises">Promises</button> <button id="reset">Reset</button> <div> <div class="items"></div> <div class="items"></div> <div class="items"></div> <div class="boxes"></div> <div class="boxes"></div> </div> <div id="results"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM