jquery的总体架构分析及实现示例详解(4)
这段代码的意思是,先执行两个操作$.ajax("test1.html")和$.ajax("test2.html"),如果都成功了,就运行done()指定的回调函数;如果有一个失败或都失败了,就执行fail()指定的回调函数。
jQuery.Deferred( func ) 的实现原理
内部维护了三个回调函数列表:成功回调函数列表、失败回调函数列表、消息回调函数列表,其他方法则围绕这三个列表进行操作和检测。
jQuery.Deferred( func ) 的源码结构:
jQuery.extend({
Deferred: function( func ) {
// 成功回调函数列表
var doneList = jQuery.Callbacks( "once memory" ),
// 失败回调函数列表
failList = jQuery.Callbacks( "once memory" ),
// 消息回调函数列表
progressList = jQuery.Callbacks( "memory" ),
// 初始状态
state = "pending",
// 异步队列的只读副本
promise = {
// done, fail, progress
// state, isResolved, isRejected
// then, always
// pipe
// promise
},
// 异步队列
deferred = promise.promise({}),
key;
// 添加触发成功、失败、消息回调函列表的方法
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// 添加设置状态的回调函数
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock )
.fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// 如果传入函数参数 func,则执行。
if ( func ) {
func.call( deferred, deferred );
}
// 返回异步队列 deferred
return deferred;
},
}
jQuery.when( deferreds )
提供了基于一个或多个对象的状态来执行回调函数的功能,通常是基于具有异步事件的异步队列。
jQuery.when( deferreds ) 的用法
如果传入多个异步队列对象,方法 jQuery.when() 返回一个新的主异步队列对象的只读副本,只读副本将跟踪所传入的异步队列的最终状态。
一旦所有异步队列都变为成功状态,“主“异步队列的成功回调函数被调用;
如果其中一个异步队列变为失败状态,主异步队列的失败回调函数被调用。
- 上一篇:初始Nodejs_node.js
- 下一篇:jquery常用方法及使用示例汇总