标签:
1 var callbacks = $.Callbacks(); 2 setTimeout(function(){ 3 console.log(1); // 1 4 callbacks.fire(); // 2 add中的方法也会执行(同步的写法,异步执行) 5 }, 1000); 6 callbacks.add(function(){ 7 console.log(2); 8 });
$.Deferred来实现上面的操作
1 var deferred = $.Deferred(); 2 setTimeout(function(){ 3 console.log(1); // 1 4 deferred.resolve();// 2 5 }, 1000); 6 deferred.done(function(){ 7 console.log(2); 8 });
1 var deferred = $.Deferred(); 2 setTimeout(function(){ 3 //deferred.resolve(); // success 4 deferred.reject(); // error 5 //deferred.notify(); // progressing 6 }, 1000); 7 deferred.done(function(){ 8 console.log(‘success‘); 9 }).fail(function(){ 10 console.log(‘error‘); 11 }).progress(function(){ 12 console.log(‘progressing‘); 13 });
下面是一个比较有意思的用法:memory的记忆功能。
1 var deferred = $.Deferred(); 2 setTimeout(function(){ 3 deferred.resolve();// 1 4 }, 100); 5 deferred.done(function(){ 6 console.log(1); 7 }); 8 $(‘#btn‘).on(‘click‘, function () { 9 deferred.done(function(){ 10 console.log(2); // 2...只要单击一次按钮就会触发一次 11 }); 12 });
1 function fn(){ 2 var deferred = $.Deferred(); 3 setTimeout(function(){ 4 deferred.resolve();// 不会触发,状态在外部被修改了。 5 }); 6 return deferred; 7 } 8 var newDeferred = fn(); 9 newDeferred.done(function(){ 10 console.log(‘success‘); 11 }).fail(function(){ 12 console.log(‘error‘); 13 }); 14 newDeferred.reject(); // error
1 function fn(){ 2 var deferred = $.Deferred(); 3 setTimeout(function(){ 4 deferred.resolve();// success 5 }); 6 return deferred.promise(); 7 } 8 var newDeferred = fn(); 9 newDeferred.done(function(){ 10 console.log(‘success‘); 11 }).fail(function(){ 12 console.log(‘error‘); 13 }); 14 newDeferred.reject(); // 报错 reject方法不存在
标签:
原文地址:http://www.cnblogs.com/tyxloveyfq/p/4309929.html