How jquery chain operations are implemented and why chained operations are _jquery

Source: Internet
Author: User
Two questions
How is the 1.jQuery chain operation implemented?
2. Why to use chain operation?
What do you think is the best answer to these two questions?

chained Operation
Principle believe that Baidu a lot of, in fact, chain operation is only through the object of the method last
return this
Return the object back, the object can certainly continue to invoke the method, so you can chain operation. So simple implementation of a
Copy Code code as follows:

Define a JS class
function Demo () {
}
Expand 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 ();
}
To implement a chain-type call
D (). SetName ("CJ"). Setage. SetName ();

But...... Why use it?
The general explanation
Save code and the code looks more elegant.
For example, if you don't have a chain, you might want to write code like this:
Copy Code code as follows:

document.getElementById ("Ele"). DoSomething ();
document.getElementById ("Ele"). Dootherthing ();

This code calls two times document.getElementById to get the elements of the DOM tree, which consumes a lot, and writes two lines, and the chain just writes one line, saving the code ...

But we can also use cached elements. Like what:
Copy Code code as follows:

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

And the two lines are not much more code than the line, and even the corresponding encapsulation makes the code more.
The worst thing is that all object methods return the object itself, which means there is no return value, which is not necessarily appropriate in any environment.
For example, we want to get a very large integer biginteger (meaning that if you save an integer that might overflow with JavaScript number), and by extension his algorithm, would it be appropriate to use a chained operation?

For example, the Operation 31415926535 * 4-271828182, if the design of the chain style of the method may be this:
Copy Code code as follows:

var result = (new BigInteger ("31415926535")). Multiply (New BigInteger ("4")). Subtract (New BigInteger ("271828182")). val ();
Console.log ("result = =" + result);

This may seem elegant, but what if we want the middle result? May be written like this:
Copy Code code as follows:

var BigInteger = new BigInteger ("31415926535");
var result1 = biginteger.multiply (New BigInteger ("4")). Val ();
var result2 = biginteger.subtract (New BigInteger ("271828182")). Val ();
Console.log ("RESULT1 = =" + Result1 + ", result2 = =" + result2);

This does not seem to be a bit elegant, and do not have a chain of operation is not different!
So if the request is the original BigInteger can not change it? Well, chained operations don't seem to satisfy this need.

so why in the end to use the chain of operation?
For a better asynchronous experience
JavaScript is a non-blocking language, so he's not blocking it, it's not blocking it, so he needs to drive it through events, asynchronously, to do something that would have blocked the process.

But asynchronous programming is a crazy thing ... It doesn't matter if the runtime is separate, but writing code is also separate ...
What are the common asynchronous programming models?
callback function
The so-called callback function, means to register a function somewhere in the system first, let the system know the existence of the function, and then, when an event occurs, call the function to respond to the event.
Copy Code code as follows:

function f (num, callback) {
if (num<0) {
Alert ("Call low-level function processing!");
Alert ("Score cannot be negative, input error!");
}else if (num==0) {
Alert ("Call low-level function processing!");
Alert ("The student may not have taken the exam!") ");
}else{
Alert ("Call high-level function processing!");
settimeout (function () {callback ();}, 1000);
}
}

Here callback is the callback function. It can be found that callback is only invoked when NUM is a non-negative number.
But the problem, if we do not look inside the function, we do not know when the callback will be called, under what circumstances call, the code generated a certain coupling, the process will produce a certain amount of confusion.

Although the callback function is a simple and easily deployable method for implementing Asynchrony, it is not good enough from the programming experience.
Event Monitoring
That is, event-driven, the order of execution depends on the order of events.
Copy Code code as follows:

function Eventtarget () {
This.handlers = {};
}
Eventtarget.prototype = {
Constructor:eventtarget,
Addhandler:function (type, handler) {
This.handlers[type] = [];
},
Fire:function () {
if (!event.target) {
Event.target = 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 a custom event implementation in JavaScript advanced programming. So we can bind the event handler by AddHandler, use fire to trigger the event, and RemoveHandler to remove the event handler function.

Although the event is decoupled, the sequence of processes is even more confusing.
chain-type asynchronous
Personally feel the most commendable chain operation is that it solves the asynchronous programming model of the implementation process is not clear problem. jquery $ (document). Ready a very good explanation of this idea. Domcotentloaded is an event in which most operations of jquery do not work until the DOM is loaded, but the jquery designer does not treat him as an event, but instead turns into a way of "selecting the object and manipulating it." $ Select Document object, ready is its method to operate. This way the process problem is very clear, in the back of the chain after the method of implementation.
Copy Code code as follows:

(function () {
var Isready=false; Determine if the Ondomready method has been executed
var readylist= [];//The method that needs to be executed is in this array first.
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.length;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.documentElement.doScroll (' left ')//can be used to perform doscroll in IE to determine whether the DOM is 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 extends the idea that each asynchronous task returns a Promise object that has a then method that allows the specified callback function.
so we can write this .
F1 (). Then (F2). then (F3);
This method we do not have to pay attention to implementation, and do not need to understand asynchronous, as long as we know how to select objects through the function, through the then operation, can be asynchronous programming.

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.