jQuery1.5带来了新的延迟对象和附带的方法.when
、.Deferred
和._Deferred
.
对于那些以前没有使用过.Deferred
的人,我已经对source for it进行了注释.
这些新方法的可能用途是什么?我们如何着手将它们融入模式?
我已经读过API和source,所以我知道它的作用.我的问题是,我们如何在日常代码中使用这些新功能?
我有一个简单的example个缓冲区类,它按顺序调用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();
};
};
我正在寻找.Deferred
和.when
的演示和可能的用法.
看到._Deferred
个这样的例子也会很高兴.
例如,链接到新的jQuery.ajax
源代码就是作弊.
我特别感兴趣的是,当我们抽象出一个操作是同步还是异步完成时,有哪些技术可用.