GitHub = GitHub = GitHub = GitHub
This code is my-jquery 1.0.4.js
I recommend reading this article to understand the Callbacks principle, because Deferred asynchronous Callbacks are based on Callbacks. Download the source code and then learn according to the article ideas, it is best to think while knocking a few times.
1. Basic Concepts
Promise/A + specification
I recommend reading the Promise/A+ specification first
Promise serves as a model that provides a solution to the concept of latency described in software engineering.
- 1.Promise represents the end result of an asynchronous operation
- 2. The primary way to interact with a Promise is by passing a function into its then method to get the final value of the Promise or the reason for the value that the Promise ultimately rejects.
- 3. A Promise must be under the following status: pending, fulfilled, rejected.
- 4. A Promise must provide a THEN method to retrieve its value or reason.
Promise and Deferred
Promise is an asynchronous programming mode proposed by ES6. You can refer to Ruan Yifeng ES6-Promise
Deferred is a callback solution proposed by jQuery, which mainly relies on Callbacks. For details, see the previous Callbacks principle.
The main problem is that when an asynchronous request is dependent on the result of another asynchronous request, or when an operation has to wait until several other operations have finished, it is more powerful to extend ajax operations to all operations, and is also used in animation and timing.
2. Start parsing Deferred
1. Apis provided by Deferred
(1) $.deferred () generates a Deferred object.
(2) deferred. Done () specifies the callback function if the operation succeeds
(3) deferred.fail() specifies the callback function if the operation fails
(4).promise() returns a promise object to see if queuing is still complete when all actions of a certain type are bound to the union.
(5) Deferred.resolve () manually changes the deferred object’s running state to “Done”, triggering the done() method immediately.
This method is the opposite of deferred.reject(). It changes the deferred object’s running state to “failed”, triggering the fail() method immediately.
(7) $.when() specifies the callback function for multiple operations. In addition to these methods, the Deferred object has two important methods that are not covered in the tutorial above.
Deferred. Then () Sometimes done() and fail() can be written together to make things easier. This is called then().
(9)deferred.progress() Calls the added handler when the Deferred object is generated.
2. JQuery encapsulation
Var DTD = $.deferred (); // Create a Deferred object varwait = function(dtd){
var tasks = function(){
alert("Executed"); dtd.resolve(); // Change the execution state of the Deferred object successfully};setTimeout(tasks,2000);
returndtd; }; // The state of the delay object determines which queue's handler $.when(wait(dtd))
.done(function(){
alert("It worked.");
}).fail(function(){
alert("Something went wrong."); }) // dtd.resolve(); Changing the execution state of the DTD causesdoneReject (); reject(); // dtd.resolve();Copy the code
The above code output:
Executed successfully
Through the above code, we can deduce how the jQuery source code is implemented.
3. Source code design ideas:
The following is only the core code snippet. For the complete code, please click source Code analysis to download
(1) Firstly, the data structure of TUPLES is defined, which is used to assemble the description of storage asynchronous delay three different state information.
/** * tuples defines an array to store descriptions of three different state information * the first argument is the state of the delayed object * the second argument is to add a handler to the queue * the third argument is to create queues of different states * the fourth argument is to record the final state information **/ var tuples = [["resolve"."done",jQuery.Callbacks("once memory"),"resolved"],
["reject"."fail",jQuery.Callbacks("once memory"),"rejected"],
["notify"."progress",jQuery.Callbacks("memory")]]
Copy the code
(2) Then define a promise to encapsulate state,then, and promise objects
promise = {
state :function() {return state;
},
then:function() {
},
promise:function(obj) {
console.log(promise);
debugger
return obj !=null ? jQuery.extend(obj,promise):promise;
}
},
Copy the code
Deferred = {}; (4) Iterate through the wrapped tuples array queue, map the second element of the array to Callbacks and give it to List, map the third element of the array to stateString to record the final state information, and map the first element of the array, the state of the delay object, to Callbacks’ Add side Method, define auxiliary methods deferred[resolveWith], Deferred [rejectWith],deferred[notifyWith], and finally call the fireWith method of Callbacks to implement the callback of the queue.
Tuples tuples.forEach(tuples tuples.forEach(function(tuple, I){var list = tuple[2]; // Get a description of the current final message // promise[done| fail | progress] these three states will get Callbacks the self reference method inside add handlers promise [tuple [1]] = list. Add; // Handle state Succeeds or failsif(stateString) {// Add the first handler list.add(function(){ // state = [resolved | rejected] state = stateString; }); } / / deferred [resolve | reject | notify] state to get the function of the time delay of reference deferred [tuple [0]] =function(){
deferred[tuple[0] + "With"] (this === deferred ? promise : this, arguments);
returnthis; }; // Call the handlers in the queue and pass them the context object deferred[tuple[0] + for binding execution"With"] = list.fireWith;
});
Copy the code
(5) Return deferred
// Make the deferred a promise
promise.promise(deferred);
return deferred;
Copy the code
(6) Define a when method
// When is a callback to the delay function of one or more objects:function(subordinate){
returnsubordinate.promise(); }});Copy the code
At this point, accomplished, jQuery source code analysis to realize the author’s data structure queue processing programming ideas
Deferred Design:
other
JQuery source code analysis series directory address: GitHub
JQuery source code analysis series is expected to write about ten, aimed at deepening the understanding of native JavaScript part of the knowledge and in-depth, JQuery core functions, selectors, Callback principle, delayed object principle, event binding, jQuery architecture, delegate design mode, DOM operation, animation queue, etc. If there is any mistake or not precise place, please be sure to give correction, thank you very much. If you like it or are inspired by it, please welcome star⭐️ to encourage the author.
Concern about the public number reply: learn to receive the front end of the latest and most complete learning materials, but also into the group and big guy together to learn and exchange