[英]jQuery: deferred/ promise
我正在嘗試從示例應用程序中找出主干(請參閱https://github.com/elfsternberg/The-Backbone-Store )。 如下面的代碼所示,該代碼使用jQuery的Deferred和promise()。 我已經閱讀了jQuery上的文檔,但是無法從下面的示例中弄清楚如何使用這些方法。 您可能需要更多代碼來回答這個問題,但是可能不需要。 這些是我對此的疑問
1)淡出完成后是否調用dfd.resolve? 如果是這樣,dfd.resolve會觸發什么?
2)通過返回promise.promise()發生了什么事; 它在調用Deferred方法嗎? 什么時候? 為什么這樣做呢? 這似乎是一種遞歸方法?
3)dfd.resolve是否有可能觸發此代碼中未顯示的其他方法?
hide: function() {
if ((":visible") === false) {
return null;
}
promise = $.Deferred(_.bind(function(dfd) {
this.el.fadeOut('fast', dfd.resolve)}, this));
return promise.promise();
},
show: function() {
if (this.el.is(':visible')) {
return;
}
promise = $.Deferred(_.bind(function(dfd) {
console.log("in promise section of show in base view");
this.el.fadeIn('fast', dfd.resolve) }, this))
return promise.promise();
}
1)淡出完成后是否調用dfd.resolve? 如果是這樣,dfd.resolve會觸發什么?
是。 jQuery.fadeOut
將回調作為參數之一。 動畫完成后,它將執行回調。 在這種情況下,它恰好是Deferred的resolve方法。
2)通過返回promise.promise()發生了什么事; 它在調用Deferred方法嗎? 什么時候? 為什么這樣做呢? 這似乎是一種遞歸方法?
這里沒有遞歸操作 。 promise
只是一個變量,其中包含對創建的Deferred對象的引用。 promise()
是jQuery.Deferred
上的一種方法,該方法返回Deferred的修改版本,該版本不允許您修改其行為。 因此,保證調用者可以確保它將始終以相同的方式執行。
3)dfd.resolve是否有可能觸發此代碼中未顯示的其他方法?
是。 Deferred僅僅是允許您注冊回調的對象。 在Deferred上調用.resolve()
將觸發完成的處理程序 ,而在調用.reject()
將觸發任何失敗的處理程序 。
一個非常速記的示例可能如下所示:
//A Deferred takes in a function that will be passed a reference
// to the Deferred object. This allows you to resolve or reject
// it at some point in the future.
var promise = $.Deferred(function(def){
setTimeout(function(){
def.resolve('Five seconds have passed!');
}, 5000);
}).promise();
//This will only get executed when the
// underlying Deferred gets resolved
promise.done(function(msg){
alert(msg); // Displays: 'Five seconds have passed!'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.