jQuery 1.5 带来了新的 Deferred 对象和附加的方法.when
,.Deferred
并且._Deferred
.
对于没有使用.Deferred
过的人,我已经注释了它的来源。
这些新方法的可能用途是什么,我们如何将它们融入模式?
我已经阅读了API和源代码,所以我知道它的作用。我的问题是我们如何在日常代码中使用这些新功能?
我有一个按顺序调用 AJAX 请求的缓冲区类的简单示例。(下一个在上一个完成后开始)。
/* Class: Buffer
* methods: append
*
* Constructor: takes a function which will be the task handler to be called
*
* .append appends a task to the buffer. Buffer will only call a task when the
* previous task has finished
*/
var Buffer = function(handler) {
var tasks = [];
// empty resolved deferred object
var deferred = $.when();
// handle the next object
function handleNextTask() {
// if the current deferred task has resolved and there are more tasks
if (deferred.isResolved() && tasks.length > 0) {
// grab a task
var task = tasks.shift();
// set the deferred to be deferred returned from the handler
deferred = handler(task);
// if its not a deferred object then set it to be an empty deferred object
if (!(deferred && deferred.promise)) {
deferred = $.when();
}
// if we have tasks left then handle the next one when the current one
// is done.
if (tasks.length > 0) {
deferred.done(handleNextTask);
}
}
}
// appends a task.
this.append = function(task) {
// add to the array
tasks.push(task);
// handle the next task
handleNextTask();
};
};
我正在寻找 and 的演示和可能的.Deferred
用途.when
。
也很高兴看到._Deferred
.
链接到jQuery.ajax
示例的新来源是作弊。
当我们抽象出一个操作是同步完成还是异步完成时,我对哪些技术可用特别感兴趣。