.promise()
.promise( [ type ], [ target ] ) 返回: Promise
描述: 返回一個(gè) Promise 對(duì)象用來觀察當(dāng)某種類型的所有行動(dòng)綁定到集合,排隊(duì)與否還是已經(jīng)完成。
-
version added: 1.6.promise( [ type ], [ target ] )
type 需要待觀察隊(duì)列類型。
target附有promise 方法的Object
.promise()方法返回一個(gè)動(dòng)態(tài)生成的Promise對(duì)象用來觀察當(dāng)某種類型的所有行動(dòng)綁定到集合,排隊(duì)與否還是已經(jīng)完成。
默認(rèn)情況下, type是"fx" ,這意味著當(dāng)選定的元素已完成所有動(dòng)畫是返回的Promise是解決的。
解決上下文和唯一的參數(shù)是哪個(gè)集合到.promise()被調(diào)用。
如果target是提供,.promise()將附加到它的方法,然后返回這個(gè)對(duì)象,而不是創(chuàng)建一個(gè)新的。這對(duì)在已經(jīng)存在的對(duì)象上附加Promise的行為非常有用。
Examples:
Example: 一個(gè)集合上使用promise,而沒有動(dòng)畫解決的promise:
var div = $( "<div />" );
div.promise().done(function( arg1 ) {
// will fire right away and alert "true"
alert( this === div && arg1 === div );
});
Example: Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on):
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 50px; width: 50px;
float: left; margin-right: 10px;
display: none; background-color: #090;
}
</style>
<script src="http://code.jquery.com/jquery-git.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$("button").bind( "click", function() {
$("p").append( "Started...");
$("div").each(function( i ) {
$( this ).fadeIn().fadeOut( 1000 * (i+1) );
});
$( "div" ).promise().done(function() {
$( "p" ).append( " Finished! " );
});
});
</script>
</body>
</html>
Demo:
Example: Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections):
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 50px; width: 50px;
float: left; margin-right: 10px;
display: none; background-color: #090;
}
</style>
<script src="http://code.jquery.com/jquery-git.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
var effect = function() {
return $("div").fadeIn(800).delay(1200).fadeOut();
};
$("button").bind( "click", function() {
$("p").append( " Started... ");
$.when( effect() ).done(function() {
$("p").append(" Finished! ");
});
});
</script>
</body>
</html>