如果您熟悉jquery内部工作原理,您可能会理解代码行:
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
]
//some codes
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
我注意到在JQuery.Callbacks
函数中调用Jquery.Deferred
时返回其self
对象。
deferred.resolveWith( document, [ jQuery ] ) calls a fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args ); // notice that fire is called in here
}
}
return this;
}
来自self
对象的,后者又从fire()
函数调用jquery.Callbacks
。
我的问题是fire()
resolveWith
如何在第三次通话中从jquery.Callbacks('memory')
抓取一个空列表。
使用这个例子,我试图解释我在这里想说的内容;
var grtObj={};
vals =jQuery.Callbacks("once memory");// first call
function toAdd(){};
vals.add(toAdd);
grtObj['practice'] = vals.fireWith;
console.log(grtObj);
//runnig grtObj['practice']() here caught val.fireWith;
valu = jQuery.Callbacks("once memory"); //run 2
function duff(){};
valu.add(duff);
grtObj['act'] = valu.fireWith;
grtObj['practice'](); //caugth function duff() added to the list with valu.add instead of the toadd function that was added when grtObj['practice'] = vals.fireWith was defined.
console.log(valu.fireWith==vals.fireWith)//false
console.log(grtObj.practice==grtObj.act)//false//-->
grtObj['practice']()
如何获取函数duff()
// grtObj.practice() caught this valu.fireWith // since the different calls of jQuery.Callbacks does not return to the same variable, it surprises me how grtObj.practice could fetch function duffA() that was added from the second call. It does not matter whether grtObj['act'] = valu.fireWith was set or not.
任何人都可以帮我解释一下吗?