我正在學習如何使用jQuery的deferred,並且我注意到使用$.when
以及.notifyWith
的問題。
我做出了表率,而無需使用$.when
和.notifyWith
作品完美
function a() {
var d = new $.Deferred,
$A = $('#A'),
$P = $('#P').progressbar();
setTimeout(function() {
$A.css('background-color', 'blue');
d.notifyWith($P, [.5]);
}, 2000);
setTimeout(function() {
$A.text('test');
d.notifyWith($P, [1]);
d.resolveWith($P, ['done']);
}, 4000);
return d.promise();
}
$('#G').click(function() {
a().progress(function(x) {
this.progressbar({
value: x * 100
});
}).done(function(x) {
alert(x)
});
});
DEMO:http://jsfiddle.net/NTICompass/3DDSa/3/
裏面.progress
,this
設置爲$P
,所以進度正常移動。
我想分裂2和setTimeout
行動統一到單獨的函數,所以我這樣做,並用$.when
的承諾合併爲一個:
(function() {
var $P = $('#P').progressbar();
window.a = function() {
var d = new $.Deferred,
$A = $('#A');
setTimeout(function() {
$A.css('background-color', 'blue');
d.notifyWith($P, [.5]);
d.resolve('a()');
}, 2000);
return d.promise();
}
window.b = function() {
var d = new $.Deferred,
$A = $('#A');
setTimeout(function() {
$A.text('test');
d.notifyWith($P, [.5]);
d.resolve('b()');
}, 4000);
return d.promise();
}
}())
$('#G').click(function() {
$.when(a(), b()).progress(function(x, y) {
this.progressbar({
value: ((x || 0) + (y || 0)) * 100
});
}).done(function(x, y) {
alert(x + ' ' + y)
});
});
DEMO:http://jsfiddle.net/NTICompass/3DDSa/16/
出於某種原因this
內.progress
是不是$P
。相反,它是延遲對象(或承諾對象,我不太確定)。爲什麼不是this
等於$P
?
1.7.2的第1336行http://code.jquery.com/jquery-1.7.2.js將作爲上下文傳遞承諾,供參考。 – 2012-08-10 19:36:56
@KevinB:那麼,這可能是(全能的)jQuery中的一個錯誤? – 2012-08-10 19:42:24
Docs do say:'deferred.notifyWith(context [,args])'「上下文作爲'this'對象傳遞給progressCallbacks。」可能是一個錯誤? – 2012-08-10 19:43:52