我知道我们可以在对象中使用“返回此值”,例如:
var $ = {
name : function(){
alert("John");
return this;
},
age : function(){
alert(21);
return this
}
}
$.name().age()
一个功能完成后,将调用下一个功能。但是在JQuery中有这样的构造:
$.get(url).done(callback).fail(callback);
这个怎么运作?方法:方法“ get”按时获取回调。默认情况下,Ajax请求是异步的。
PS我对没有$ .Defferred对象的实现感兴趣。
谢谢。
这里是如何$.get(url).done(callback);
工作的。
$.get()
返回一个对象。一旦异步ajax调用开始,它将立即返回该对象(它不会等到ajax调用完成之后)。该对象有许多方法,其中包括jQuery Promise方法。这些方法之一是.done()
。当您调用.done(callback)
该返回的对象时,它将回调存储在该返回的对象的回调列表中。
当$.get()
函数在以后的某个时间完成时,这是.resolves()
它自己的承诺,最终将查找.done()
存储在对象中的所有回调,并一次调用一个回调。
因此,在此事件序列中,.done()
实际上在$.ajax()
完成ajax调用之后立即被调用,但是.done()
在其执行时,所有要做的就是存储回调,以供$.ajax()
异步操作完成后使用。
无论您是否知道,在使用$.get(url).done(callback)
构造时,都在使用jQuery Promise对象和Promise API。它的工作原理很简单,因为在这里$.get()
为你创建的承诺对象(和回报,并会再.resolve()
或者.fail()
它更高版本)和所有你需要做的就是指定.done()
,.fail()
或.then()
回调和大部分的工作是为你做。您不必手动创建一个延迟对象或Promise对象-您只需使用ajax调用返回的对象即可。
这是一个异步队列,它使用自己的.done()
处理程序支持视觉效果的链接:http : //jsfiddle.net/jfriend00/tS8G3/
function domWrapper(elem) {
if (!(this instanceof domWrapper)) {
return new domWrapper(elem);
}
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
this.elem = elem;
this.q = [];
this.timer = null;
this.doneCallbacks = [];
}
domWrapper.prototype = {
hide: function() {
this.q.push({op: "hide"});
this._exec();
return this;
},
show: function() {
this.q.push({op: "show"});
this._exec();
return this;
},
delay: function(t) {
this.q.push({op: "delay", time: t});
this._exec();
return this;
},
done: function(fn) {
this.doneCallbacks.push(fn);
return this;
},
_exec: function() {
var next;
while (!this.timer && this.q.length) {
next = this.q.shift();
switch(next.op) {
case "show":
this.elem.style.display = "block";
break;
case "hide":
this.elem.style.display = "none";
break;
case "delay":
var self = this;
this.timer = setTimeout(function() {
self.timer = null;
self._exec();
}, next.time);
break;
}
}
// if all done with all pending activities
if (!this.q.length && !this.timer) {
// call the done callbacks
for (var i = 0; i < this.doneCallbacks.length; i++) {
this.doneCallbacks[i].call(this.elem);
}
}
}
}
function makeBlue() {
this.style.backgroundColor = "blue";
}
function makeBigger() {
this.style.width = "200px";
}
domWrapper("test").done(makeBlue).done(makeBigger)
.delay(2000).hide().delay(2000).show().delay(1000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句