jquery Basic Teaching thread deferred object use method

Source: Internet
Author: User
Tags advantage

 jquery Basic teaching Deferred object usage

One, what is the deferred object? During the   development of the Web site, we often experience some very long javascript operations. There are both asynchronous operations (such as AJAX reading Server data), and synchronous operations (such as traversing a large array), none of which can immediately result.   The usual practice is to specify a callback function (callback) for them. That is, in advance, which functions should be called once they are finished.   However, jquery has a very weak function in terms of callback functions. To change this, the jquery development team designed the deferred object.   Simply put, the deferred object is the callback function solution for jquery. In English, defer means "delay", so the meaning of the deferred object is "delay" to a certain point in the future.   It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface. Its main function can be summed up to four points. Here we go through the example code, step-by-step learning.   Second, the chain style of Ajax operation   First, review the traditional way of jquery Ajax operation:     Code as follows: $.ajax ({url: "test.html", Success:function () {alert ("Haha, success!") ");  }, Error:function () {alert ("Error!") "); }  });       In the above code, $.AJAX () accepts an object parameter that contains two methods: The Success method specifies the callback function after the operation succeeds, and the error method specifies the callback function after the operation fails.   $.ajax () after the operation is completed, if you are using jquery less than version 1.5.0, you will not be able to perform chain operations, if you are working with a XHR object, and if you are above the 1.5.0 version, you are returning a deferred object, which can be chained.   Now, the new writing is this:     code is as follows: $.ajax ("test.html")  . Done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });       can be seen, done () equivalent to sucCess method, fail () is equivalent to the error method. With the chain style, the readability of the code is greatly improved.   Third, one of the great benefits of specifying multiple callback functions for the same operation   deferred objects is that it allows you to add multiple callback functions freely.   The above code as an example, if the Ajax operation succeeded, in addition to the original callback function, I would like to run a callback function, how to do?   is simple, just add it to the back of the line.   Code as follows: $.ajax ("test.html"). Done (function () {alert ("Haha, success!"). ");} ) . Fail (function () {alert ("Error!) "); } ) . Done (function () {alert ("Second callback function!) ");} ); The     callback function can add as many as you want, and they are executed in the order in which they were added.   The other great benefit of specifying callback functions   deferred objects for multiple operations is that it allows you to specify a callback function for multiple events, which is not possible with traditional writing.   See the code below, which uses a new method $.when ():   Code as follows: $.when ($.ajax ("test1.html"), $.ajax ("test2.html")). Done (function () { Alert ("Haha, success!") "); }) . Fail (function () {alert ("Error!) "); });     This code means that two actions $.ajax ("test1.html") and $.ajax ("test2.html") are executed first, and if all succeeds, the done () specified callback function is run; if one fails or fails, Executes the callback function specified by fail (). The great advantage of the   v. Common Operation callback function interface (top)   Deferred object is that it extends this set of callback function interfaces from Ajax operations to all operations. That is, any operation----either an AJAX or a local operation, whether asynchronous or synchronous----can use various methods of the deferred object to specify the callback function.   Let's look at a concrete example. Suppose there is a time-consuming operation wait:     code is as follows: var wait = function () {  VAR tasks = function () {  Alert ("Execution completed!") ");  };   settimeout (tasks,5000);  };       We specify a callback function for it, what should we do?   Naturally, you will think that you can use $.when ():     Code as follows: $.when (Wait ())  . Done (function () {alert ("Haha, successful!") "); })   Fail (function () {alert ("error)!" "); });       However, in this case, the done () method executes immediately and does not function as a callback function. The reason is that the $.when () parameter can only be a deferred object, so the wait () must be overwritten: The   code is as follows: the 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;  };       Now, the Wait () function returns the deferred object, which can be combined with a chained operation.     Code as follows: $.when (Wait (DTD))  -Done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); }); After the       wait () function runs, it automatically runs the callback function specified by the done () method.   VI, Deferred.resolve () method and Deferred.reject () method   If you look closely, you will find that there is another place in the wait () function that I did not explain. That is the Dtd.resolve ()What is the role?   to be clear about this, a new concept, "State of Execution", will be introduced. jquery stipulates that the deferred object has three execution states----incomplete, completed, and failed. If the execution status is completed (resolved), the deferred object immediately invokes the callback function specified by the done () method, or the callback function specified by the fail () method if the execution state is "failed", and continues waiting if the execution state is "incomplete". or call the callback function specified by the progress () method (added by the jQuery1.7 version).   The Ajax operation in the previous section, the deferred object automatically changes its execution state based on the return result, but in the wait () function, the execution state must be manually specified by the programmer. Dtd.resolve () means that the execution state of a DTD object is changed from incomplete to completed, triggering the Done () method.   Similarly, there is also a deferred.reject () method that triggers the Fail () method by changing the execution state of the DTD object from "incomplete" to "failed". The   code is as follows: var DTD = $. Deferred (); Create a new Deferred object   var wait = function (DTD) {  var tasks = function () {  Alert ("Execution completed!") ");   Dtd.reject (); Change the execution status of the deferred object  };   settimeout (tasks,5000);   Return DTD;  };   $.when (Wait (DTD))   Done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });       VII, Deferred.promise () method   The above writing, there is still a problem. That is, the DTD is a global object, so its execution state can be changed from the outside.   See the code below: The code is as follows: 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;  };   $.when (Wait (DTD))   Done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });   Dtd.resolve ();       I added a line of Dtd.resolve () to the end of the code, which changed the execution state of the DTD object, resulting in the execution of the done () method immediately, jumping out of the "Haha, success!" "Prompt box, wait 5 seconds before jumping out" execution completed! Prompt box.   To avoid this, jquery provides the Deferred.promise () method. Its role is to return another deferred object on the original deferred object, which only opens methods unrelated to changing the execution state (such as the Done () method and the Fail () method), shielding the methods associated with changing the execution state (e.g. resolve () Method and The Reject () method) so that the execution state cannot be changed.   See the following code: The   code is as follows: 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 (); Returns the Promise object  };   var d = Wait (DTD); Creates a new D object, operates on this object   $.when (d)  . Done (function () {alert ("Haha, success!")"); })   Fail (function () {alert ("error)!" "); });   D.resolve (); At this point, the statement is invalid       in the above code, the Wait () function returns the Promise object. We then bind the callback function above the object, not the original deferred object. The advantage is that you cannot change the execution state of this object, and you can only manipulate the original deferred object if you want to change the state of execution.   However, a better way to do this is to allenm the DTD object into the internal object of the wait () function. The   code is as follows: var wait = function (DTD) {  var DTD = $. Deferred (); Inside the function, create a new deferred object   var tasks = function () {  alert ("Execute!"). ");   Dtd.resolve (); Change the execution status of the deferred object  };   settimeout (tasks,5000);   return dtd.promise (); Returns the Promise object  };   $.when (Wait ())   Done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });       VIII. common operation callback function interface (middle)   Another way to prevent the execution state from being externally altered is to use the constructor $ of the deferred object. Deferred ().   At this point, the wait function remains the same, and we pass it directly into $. Deferred ():     Code is as follows: $. Deferred (Wait)   done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });       jquery rules, $. Deferred () can accept a function name (note, is the name of the functions)As a parameter, $. The Deferred object generated by Deferred () will be the default argument for this function.   IX, normal operation of the callback function interface (bottom)   In addition to the above two methods, we can also directly deploy the deferred interface on the wait object.     Copy code code as follows: var DTD = $. Deferred (); Generate 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);  };   Dtd.promise (wait);   Wait.done (function () {alert ("Haha, success!") "); })   Fail (function () {alert ("error)!" "); });   Wait (DTD);       The key here is the dtd.promise (wait) line, which is the role of deploying the deferred interface on the wait object. It is because of this line that you can invoke the done () and fail () directly above the wait.   10, Summary: Deferred object method   has already talked about several methods of deferred object, the following is a summary:   (1) $. Deferred () generates a Deferred object.   (2) Deferred.done () specifies the callback function when the operation succeeds   (3) Deferred.fail () specifies the callback function when the operation fails   (4) deferred.promise () when there is no parameter, returns a new Deferred object in which the running state of the object cannot be changed, and when the parameter is accepted, the function is to deploy the deferred interface on the Parameter object.   (5) deferred.resolve () manually change the running state of the deferred object to "completed", triggering the Done () method immediately.   (6) Deferred.reject () This methodIn contrast to Deferred.resolve (), The Fail () method is immediately triggered by changing the running state of the deferred object to "failed" after the call.   (7) $.when () specifies a callback function for multiple operations.   In addition to these methods, the deferred object has two important methods, which are not covered in the tutorials above.   (8) Deferred.then ()   Sometimes for the sake of convenience, can be done () and fail () together to write, 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, then it is equivalent to done ().   (9) deferred.always ()   This method is also used to specify a callback function, which is always executed regardless of whether the call is Deferred.resolve () or Deferred.reject (). The   code is as follows: $.ajax ("test.html")  . Always (function () {alert ("Executed!"). ");} );  

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.