But when we write our own jQuery code, we rarely pay attention to or use pushStack(). If we need to write a plug-in involving DOM traversal, it will be especially useful.
Inside jQuery, pushStack The () method "tracks" the DOM result set returned by the previous method in the chain call by changing the prevObject property of a jQuery object (it is encapsulated by jQuery and is also a jQuery object. It is said to be "tracked" because what is actually stored is a Reference). When we call the end() method in a chain, the prevObject of the current jQuery object is returned internally. For more details, just look at the source code. Here is just a simple analysis, and here is an example:
html:
I am grandparent.
I am parent.
I am child .
javascript:
var els = $('#child').parent().parent();
console.dir( els);
Illustration:
After understanding this, we will make a grandparent plug-in to replace .parent().parent() for two consecutive calls. Use .grandparent() directly. If "accidentally" "If end() is not considered, the code is likely to look like this:
$.fn.grandparent = function() {
return this.parent().parent();
};
Still using the above example :
$('#child').grandparent() .end(); //jQuery-[div#parent]
Obviously, in most cases this is not what we want, in fact we want to return directly through chained end() calls Go to jquery[div#child]. Now it’s time for pushStack to take action. We just need to add one line:
$.fn.grandparent = function() {
var els = this.parent().parent();
return this.pushStack( els.get());
};
Inside pushStack, encapsulate the DOM array returned by els.get() into a new jQuery object, and this(jQuery[div# child]) will be assigned to the prevObject of the newly constructed jQuery before, and finally return the new jQuery object.
So this time, when we use end() again:
var grandparent = $('#child').grandparent()./* jquery-[ div#grandparent]*/.end() /*jquery-[div#child]*/
The main idea of this blog post comes from a blog in Learning JQuery. Thanks to the author for sharing. If you are interested, click jQuery pushStack.