jQuery Deferred 回调 最简 教程

Deferrd是jQuery提供的回调方法包装类。

以下内容摘自jQuery Api 1.7
function asyncEvent() {
var dfd = new jQuery.Deferred();

// Resolve after a random interval
setTimeout(function () {
dfd.resolve("hurray"); //触发成功事件 | 被done注册的函数
}, Math.floor(400 + Math.random() * 2000));

// Reject after a random interval
setTimeout(function () {
dfd.reject("sorry"); //触发失败事件 | 被fail注册的函数
}, Math.floor(400 + Math.random() * 2000));

// Show a "working..." message every half-second
setTimeout(function working() {
if (dfd.state() === "pending") {
dfd.notify("working... "); //触发progress事件
setTimeout(working, 500);
}
}, 1);//精彩的代码
// Return the Promise so caller can't change the Deferred
return dfd.promise(); //删掉用于触发的方法:reject,resolve,notify
}

asyncEvent().done(function () {
console.log('成功');
}).fail(function () {
console.log('失败');
}).always(function () {
console.log('不管成败,反正是结束了');
}).progress(function () {
console.log('you got a message~');
});


还有一些方便使用的函数:$.when(dfd1,[dfd2,[dfd3]]),他返回的还是Deferrd对象。当传入的所有dfd都成功后,才会触发done事件。当任意一个dfd失败,立即触发fail



var a=$.Deferred();
var b=$.Deferred();

$.when(a,b)
.fail(function(){console.log('失败');})
.done(function(){console.log('成功');});

b.resolve()
a.resolve()
//输出:成功



var a=$.Deferred();
var b=$.Deferred();

$.when(a,b)
.fail(function(){console.log('失败');})
.done(function(){console.log('成功');});

b.reject()
//输出:失败


then是一个快捷方法:dfd.then(doneCallback,failCallback,[progressCallback]);

还有:在所有的触发用方法都可以传递一个参数

// Attach a done, fail, and progress handler for the asyncEvent
$.when(asyncEvent()).then(function (status) { //注册成功回调,done
console.log(status + ', things are going well');
}, function (status) { //注册失败回调,fail
console.log(status + ', you fail this time');
}, function (status) { //注册progress回调。1.7新增
$("body").append(status);
});



最后说精彩的代码:[url]http://p2world.iteye.com/blog/1405227[/url]

[url]http://p2world.iteye.com/blog/1405238[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值