JQuery deferred object usage details _ jquery-js tutorial

Source: Internet
Author: User
JQuery is developed quickly. It has a major version every six months and a minor version every two months. Each version introduces some new features. What I want to introduce today is a new feature introduced from jQuery1.5.0-the deferred object.

This function is very important and will become the core method of jQuery in the future. It completely changes how to use ajax in jQuery. All ajax code of jQuery has been rewritten to implement it.

However, it is abstract, difficult for beginners to master, and there are not many online tutorials. Therefore, I sorted out my study notes, hoping to help you.

This document is not a preliminary tutorial, but intended for developers who already have jQuery experience. If you want to know the basic usage of jQuery, read my jQuery design ideas and jQuery best practices.

1. What is a deferred object?

During website development, we often encounter some javascript operations that take a long time. Both asynchronous operations (for example, ajax reading server data) and synchronous operations (for example, traversing a large array) do not result immediately.

The usual solution is to specify the callback function for them ). Which functions should be called once they are finished.

However, jQuery has very weak functions in callback functions. To change this, the jQuery development team designed the deferred object.

Put simply, the deferred object is jQuery's callback function solution. In English, defer means "delay", so the deferred object means "delay" to a certain point in the future.

It solves the problem of time-consuming operations, provides better control over those operations, and unified programming interfaces. Its main functions can be summarized as four points. Next we will learn through the sample code step by step.

Ii. Link Writing of ajax operations

The traditional method of jQuery's ajax operations is as follows:

$. Ajax ({

Url: "test.html ",

Success: function (){
Alert ("Haha, success! ");
},

Error: function (){
Alert ("error! ");
}

});

(Run sample code 1)

In the code above, $. ajax () accepts an object parameter. This object contains two methods: The success method specifies the callback function after the operation is successful, and the error method specifies the callback function after the operation fails.

$. After ajax () is completed, if jQuery of version 1.5.0 or earlier is used, the returned XHR object cannot be chained. If jQuery of version 1.5.0 or later is returned, the deferred object is returned, you can perform chained operations.

Now, the new method is as follows:

$. Ajax ("test.html ")

  . Done (function () {alert ("Haha, success! ");})

  . Fail (function () {alert ("error! ");});

(Run sample code 2)

As you can see, done () is equivalent to the success method, and fail () is equivalent to the error method. After the code is chained, the code readability is greatly improved.

3. Specify multiple callback functions for the same operation

A major benefit of the deferred object is that it allows you to add multiple callback functions freely.

The above code is used as an example. If I want to run another callback function after the ajax operation is successful, what should I do?

It's easy. Just add it to the back.

$. Ajax ("test.html ")

. Done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");})

  . Done (function () {alert ("Second callback function! ");});

(Run sample code 3)

Multiple callback functions can be added, which are executed in the order of addition.

4. Specify the callback function for multiple operations

Another major benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not traditionally written.

See the following code. It uses a new method $. when ():

  $. When ($. ajax ("test1.html"), $. ajax ("test2.html "))

. Done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");});

(Sample code 4)

This Code indicates that two operations are performed first $. ajax ("test1.html") and $. ajax ("test2.html"). If it succeeds, run the callback function specified by done (). If one fails or both, run the callback function specified by fail.

5. Callback Function interfaces for common operations (I)

The biggest advantage of the deferred object is that it extends this callback function interface from ajax operations to all operations. That is to say, any operation, whether ajax or local, asynchronous or synchronous, can use various methods of the deferred object to specify the callback function.

Let's look at a specific example. Assume that there is a very time-consuming wait operation:

Var wait = function (){

Var tasks = function (){

Alert ("execution completed! ");

};

SetTimeout (tasks, 5000 );

};

What should we do if we specify a callback function for it?

Naturally, you will think that you can use $. when ():

$. When (wait ())

. Done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");});

However, there is a problem. $. When () can only be a deferred object, so you must rewrite wait:

Var dtd = $. Deferred (); // create a new deferred object

Var wait = function (dtd ){

Var tasks = function (){

Alert ("execution completed! ");

      Dtd. resolve (); // Change the execution status of the deferred object

};

SetTimeout (tasks, 5000 );

    Return dtd. promise ();

};

Note the following two points.

First, the last line cannot directly return the dtd, And the dtd. promise () must be returned (). The reason is that jQuery requires that any deferred object has three execution states: incomplete, completed, and failed. If you directly return the dtd, the default execution status of $. when () is "completed", and the subsequent done () method is immediately triggered, this will lose the function of the callback function. The purpose of dtd. promise () is to ensure that the current execution status-that is, "unfinished"-remains unchanged, so that the callback function is triggered only after the operation is completed.

Second, after the operation is complete, you must manually change the execution status of the Deferred object. Otherwise, the callback function cannot be triggered. The function of dtd. resolve () is to change the execution status of the dtd from "unfinished" to "completed" to trigger the done () method.

Finally, do not forget to pass in the dtd parameter directly when calling wait after modification.

$. When (wait (dtd ))

. Done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");});

(Run sample code 5)

6. Callback Function interfaces for common operations (medium)

In addition to adding a callback function for a common operation using $. when (), you can also use the construction function $. deferred () of the Deferred object ().

At this time, the wait function remains unchanged, and we pass it directly to $. Deferred ():

  $. Deferred (wait)

. Done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");});

(Run code example 6)

JQuery stipulates that $. Deferred () can accept a function as a parameter, which will be executed before $. Deferred () returns the result. In addition, the Deferred object generated by $. Deferred () will be used as the default parameter of this function.

VII. Callback Function interfaces for common operations (below)

In addition to the above two methods, we can also directly deploy the deferred interface on the wait object.

Var dtd = $. Deferred (); // generate a Deferred object

Var wait = function (dtd ){

Var tasks = function (){

Alert ("execution completed! ");

Dtd. resolve (); // Changes the execution status of the Deferred object

};

SetTimeout (tasks, 5000 );

};

  Dtd. promise (wait );

Wait. done (function () {alert ("Haha, success! ");})

. Fail (function () {alert ("error! ");});

Wait (dtd );

(Run sample code 7)

The key here is the dtd. promise (wait) line. Its function is to deploy the Deferred interface on the wait object. Only with this line can done () and fail () be called directly on wait ().

VIII. Summary: deferred object Method

We have discussed several methods for the deferred object. The following is a summary:

(1) $. Deferred () generates a deferred object.

(2) deferred. done () specifies the callback function when the operation is successful.

(3) deferred. fail () specifies the callback function when the operation fails.

(4) When deferred. promise () does not have a parameter, the function is to keep the running state of the deferred object unchanged. When the parameter is accepted, the function is to deploy the deferred interface on the parameter object.

(5) deferred. resolve () manually changes the running status of the deferred object to "completed", and immediately triggers the done () method.

(6) $. when () specifies the callback function for multiple operations.

In addition to these methods, the deferred object has three important methods that are not covered in the previous tutorial.

(7) deferred. then ()

Sometimes, you can combine done () and fail () to save trouble. This is the then () method.

$. When ($. ajax ("/main. php "))

  . Then (successFunc, failureFunc );

If then () has two parameters, the first parameter is the callback function of the done () method, and the second parameter is the callback method of the fail () method. If then () has only one parameter, it is equivalent to done ().

(8) deferred. reject ()

This method is opposite to deferred. resolve (). After the call, the running status of the deferred object is changed to "failed", and the fail () method is triggered immediately.

(9) deferred. always ()

This method is also used to specify the callback function. Its function is to always execute whether deferred. resolve () or deferred. reject () is called.

$. Ajax ("test.html ")

. Always (function () {alert ("executed! ");});

(End)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.