How to Implement jQuery chained operations and why to use chained operations _ jquery-js tutorial

Source: Internet
Author: User
How is jQuery implemented by chained operations? Why do I need to perform chained operations? We will help you solve these two problems. If you are interested, you can understand them. Two Problems
1. How does jQuery perform chained operations?
2. Why do I need to perform chained operations?
Which of the following questions can be answered?

Chain Operation
I believe that Baidu is a bit tricky. In fact, chained operations are only the last step through the object method.
Return this
Return the object back. Of course, the object can continue to call the method, so it can be chained. So, Simple implementation:

The Code is as follows:


// Define a JS class
Function Demo (){
}
// Extend its prototype
Demo. prototype = {
SetName: function (name ){
This. name = name;
Return this;
},
GetName: function (){
Return this. name;
},
SetAge: function (age ){
This. age = age;
Return this;
}
};
//// Factory function
Function D (){
Return new Demo ();
}
// Implement chained call
D (). setName ("CJ"). setAge (18). setName ();


But ...... Why?
General Explanation:
Saves on the amount of code and the code looks more elegant.
For example, if there is no chain, you may need to write the code like this:

The Code is as follows:


Document. getElementById ("ele"). dosomething ();
Document. getElementById ("ele"). dootherthing ();


This Code calls document. getElementById twice to get the elements of the DOM tree, which consumes a lot and requires two lines. Instead, you only need to write one line for the chain, saving the code ......

But we can also use cache elements. For example:

The Code is as follows:


Var ele = document. getElementById ("ele ");
Ele. dosomething ();
Ele. dootherthing ();


In addition, the two lines do not have much code than one line, and even the corresponding encapsulation makes the code more.
The worst thing is that all object Methods return the object itself, that is, no return value, which is not necessarily applicable in any environment.
For example, we want to create a big integer BigInteger (meaning that if Javascript Number is used to save the integer that may overflow), and expand its calculation method by the way, will it be suitable for chained operations?

For example, if the calculation is 31415926535*4-271828182, the method designed as a chain style may be like this:

The Code is as follows:


Var result = (new BigInteger ("31415926535"). multiply (new BigInteger ("4"). subtract (new BigInteger ("271828182"). val ();
Console. log ("result =" + result );


This seems elegant, but what should we do if we want intermediate results? It may be written as follows:

The Code is as follows:


Var bigInteger = new bigint ("31415926535 ");
Var result1 = bigInteger. multiply (new BigInteger ("4"). val ();
Var result2 = bigInteger. subtract (new BigInteger ("271828182"). val ();
Console. log ("result1 =" + result1 + ", result2 =" + result2 );


This seems to be not elegant at all, and it is no different from chained operations!
So what if the requirement is that the original BigInteger cannot be changed? Well, the chain operation does not seem to meet this requirement.

So why do we need to perform chained operations?
For better asynchronous experience
Javascript is a non-blocking language, so it is not blocking, but not blocking, so it needs to be driven by events, asynchronous to complete some operations that need to block the process.

But asynchronous programming is a crazy thing ...... It doesn't matter if the code is separated during running, but the code is also separated ......
What are common asynchronous programming models?
Callback Function
The so-called callback function means to register the function in a certain part of the system to let the system know the existence of the function. Then, when an event occurs in the future, call this function to respond to the event.

The Code is as follows:


Function f (num, callback ){
If (num <0 ){
Alert ("calls lower-level function processing! ");
Alert ("the score cannot be negative. incorrect input! ");
} Else if (num = 0 ){
Alert ("calls lower-level function processing! ");
Alert ("this student may not take the test! ");
} Else {
Alert ("calls high-level function processing! ");
SetTimeout (function () {callback () ;}, 1000 );
}
}


Here, callback is the callback function. It can be found that callback is called only when num is not negative.
However, if we don't look at the function, we don't know when the callback will be called. Under what circumstances will the code be coupled and the process will also be confused.

Although the callback function is a simple and easy-to-deploy method to implement Asynchronization, it is not good in programming experience.
Event listening
That is, event-driven execution depends on the event sequence.

The Code is as follows:


Function EventTarget (){
This. handlers = {};
}
EventTarget. prototype = {
Constructor: EventTarget,
AddHandler: function (type, handler ){
This. handlers [type] = [];
},
Fire: function (){
If (! Event.tar get ){
Event.tar get = this;
}
If (this. handlers [event. type instanceof Array]) {
Var handlers = this. handlers [event. type];
For (var I = 0, len = handlers. length, I <len; I ++ ){
Handlers [I] (event );
}
}
},
RemoveHandler: function (type, handler ){
If (this. handlers [type] instanceof Array ){
Var handlers = this. handlers [type];
For (var I = 0, le = handlers. length; I <len; I ++ ){
If (handlers [I] === handler ){
Break;
}
}
Handlers. splice (I, 1 );
}
}
};


The above is the implementation of custom events in JavaScript advanced programming. So we can use addHandler to bind the event handler, use fire to trigger the event, and use removeHandler to delete the event handler.

Although events are decoupled, the Process Order is even more chaotic.
Chained asynchronous
I personally think that chained operations are the most commendable solution to the unclear execution process of asynchronous programming models. $ (Document). ready In jQuery explains this idea very well. DOMCotentLoaded is an event. Before DOM is loaded, most jQuery operations won't work, but jQuery designers didn't treat it as an event, instead, it is converted into an idea of "selecting an object and operating on it. $ The document Object is selected, and ready is its method for operations. In this way, the process problem is very clear, and the method after the chain is located is executed.

The Code is as follows:


(Function (){
Var isReady = false; // checks whether the onDOMReady method has been executed.
Var readyList = []; // Save the method to be executed in this array
Var timer; // timer handle
Ready = function (fn ){
If (isReady)
Fn. call (document );
Else
ReadyList. push (function () {return fn. call (this );});
Return this;
}
Var onDOMReady = function (){
For (var I = 0; I ReadyList [I]. apply (document );
}
ReadyList = null;
}
Var bindReady = function (evt ){
If (isReady) return;
IsReady = true;
OnDOMReady. call (window );
If (document. removeEventListener ){
Document. removeEventListener ("DOMContentLoaded", bindReady, false );
} Else if (document. attachEvent ){
Document. detachEvent ("onreadystatechange", bindReady );
If (window = window. top ){
ClearInterval (timer );
Timer = null;
}
}
};
If (document. addEventListener ){
Document. addEventListener ("DOMContentLoaded", bindReady, false );
} Else if (document. attachEvent ){
Document. attachEvent ("onreadystatechange", function (){
If (/loaded | complete/). test (document. readyState ))
BindReady ();
});
If (window = window. top ){
Timer = setInterval (function (){
Try {
IsReady | document.doc umentElement. doScroll ('left'); // you can run doScroll in IE to determine whether the dom has been loaded.
} Catch (e ){
Return;
}
BindReady ();
}, 5 );
}
}
})();


The above Code cannot use $ (document). ready, but should be window. ready.
Promise
The asynchronous programming model in CommonJS also continues this idea. Each asynchronous task returns a Promise object, which has a then method that allows you to specify a callback function.
So we can write:
F1 (). then (f2). then (f3 );
In this way, we do not need to pay too much attention to implementation or understand Asynchronization. As long as we know how to select objects through functions and perform operations through then, we can implement asynchronous programming.
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.