首页 > 代码库 > jquery1.7.2的源码分析(三)$.Deferred
jquery1.7.2的源码分析(三)$.Deferred
例子的详细讲解
<script> var filterResolve = function() { var defer = $.Deferred(), filtered = defer.then(function( value ) { return value * 2; }); defer.resolve( 5 ); filtered.done(function( value ) { $( "p" ).html( "Value is ( 2*5 = ) 10: " + value ); }); }; $( "button" ).on( "click", filterResolve );</script>
上面的的代码是怎么运行的呢
点击button的先执行 $.Deferred(),得到具有很多方法的defer
defer.resolve( 5 );
var doneList = jQuery.Callbacks( "once memory" ),failList = jQuery.Callbacks( "once memory" ),progressList = jQuery.Callbacks( "memory" ),state = "pending";lists = {resolve: doneList,reject: failList,notify: progressList}for ( key in lists ) {deferred[ key ] = lists[ key ].fire;deferred[ key + "With" ] = lists[ key ].fireWith;}//根据上面的代码可得//deferred[ ‘resolve‘]=lists[ ‘resolve‘].fire;//deferred[ ‘resolveWidth‘]=lists[ ‘resolve‘].fireWith;//deferred[ ‘reject‘]=lists[ ‘reject‘].fire;//deferred[ ‘rejectWidth‘]=lists[ ‘reject‘].fireWith;//deferred[ ‘notify‘]=lists[ ‘notify‘].fire;//deferred[ ‘notifyWidth‘]=lists[ ‘notify‘].fireWith;//因此resolve( 5 )执行了
fire: function() { self.fireWith( this, arguments ); return this;},fireWith: function( context, args ) {//stack=[];为true;firing 为false;flag={} if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); }//memory =undefined } else if ( !( flags.once && memory ) ) { fire( context, args ); } } return this;}
fire = function( context, args ) { args = args || [];//memory = [ context, args ];即为self,和5 memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) {//函数执行后为false并且flags.stopOnFalse 为true时memory = true;//注意这里执行了函数 if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else {//最终又把list函数组给赋值为空 list = []; } } }
jquery1.7.2的源码分析(三)$.Deferred
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。