Using PushStack() In jQuery Plugins To Create New Collections

Posted October 29, 2009 at 9:58 AM by Ben Nadel

Tags: Javascript / DHTML

Most of the time, when creating a plugin in jQuery, I'll leverage built-in functions like filter() and each() to select from or alter the current collection. Plugins that are built in this fashion are auto-wired to have the appropriate stack connections; that is, since jQuery performs non-destructive collection augmentation, when you use a plugin that is built on top of these methods, you can then use the end() method to move back up the collection stack to the previous collection. Occassionally, however, I have the need to create a plugin that builds an entirely new collection that is not an augmented version of the current collection; as such, there is no auto-wiring of the collection chain.

In cases like that, you need to manually create the collection relationship. jQuery provides the pushStack() method for such scenarios. When you call pushStack() off of the current collection, it will take the given collection and associate it to the current collection such that calling the end() method (after the plugin exits) will return the programmer to the current collection.

Let's take a look at a small example:

  • <!DOCTYPE HTML>
  • <html>
  • <head>
  • <title>Using PushStack In jQuery Plugins</title>
  • <script type="text/javascript" src="jquery-1.3.2.js"></script>
  • <script type="text/javascript">
  •  
  • // This plugin gets the PREV and NEXT siblings of the
  • // elements in the current collection and pushes it
  • // onto the stack so that end() will return to original
  • // collection.
  •  
  • jQuery.fn.near = function(){
  • // Get a new collection of elements consisting of the
  • // merging of the PREV and NEXT elements.
  • var newCollection = this.prev().add( this.next() );
  •  
  • // When we return this new collection, push it onto
  • // the stack. This will appropriate set the prevObject
  • // proprety of the new collection.
  • return(
  • this.pushStack(
  • newCollection,
  • "near",
  • ""
  • )
  • );
  • };
  •  
  •  
  • // --------------------------------------------------- //
  • // --------------------------------------------------- //
  •  
  •  
  • // When the DOM is ready, initialize.
  • jQuery(function( $ ){
  •  
  • $( "li.start" )
  • .near()
  • .css( "font-style", "italic" )
  • .end()
  • .css( "font-weight", "bold" )
  • ;
  •  
  • });
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Using PushStack In jQuery Plugins
  • </h1>
  •  
  • <ol>
  • <li>
  • First list item.
  • </li>
  • <li class="start">
  • Second list item.
  • </li>
  • <li>
  • Third list item.
  • </li>
  • </ol>
  •  
  • </body>
  • </html>

Here, we are creating a new jQuery plugin, near(), that returns the aggregation of the prev() and next() elements. When we run the above code, we get the following output:

First list item.
Second list item.
Third list item.

You'll notice that we started with the middle LI and then called the near() plugin method. This returned the first and third list items, which we italicized. We then called end(), moving back to the original collection (li.start), which we then made bold.

Of the arguments passed to the pushStack() method, only the first, which is the new collection, is critical. The second and third arguments which are the Name of the plugin and the Selector that it uses respectively, seem to be used only to set the internal "selector" property.

This is the first time that I have used the pushStack() method, so forgive me if I have gotten something wrong or provided some misinformation. However, based on my demo above, this seems to work quite nicely.



Reader Comments

Oct 30, 2009 at 7:44 AM // reply »
11 Comments

Nice write-up Ben! Before I knew about pushStack() I used to just return a new jQuery collection, i.e.

jQuery.fn.plugin = function(){ return $(something); }

It worked in most cases but obviously didn't retain the original jQuery instance. This can be misleading - the jQuery instance really shouldn't change half way through a chain.

pushStack() is the ideal way to do this because it doesn't remove or create a new object, it simply modifies the current one.

I hope others will take this into account when creating plugins that change the collection.


Oct 30, 2009 at 7:54 AM // reply »
11,246 Comments

@James,

I think the real problem is that there's like ZERO documentation on this method. In fact, if you even go to the plugin authoring section of the jQuery website, they don't even mention this. I am not sure why exactly - it seems like a really key concept.


Nov 17, 2010 at 12:01 PM // reply »
2 Comments

Your exemple is doesn't work:
(with FireBug)
styntax error
var newCollection = this.prev().add( this.next() );

La doc est complètement vide sur la méthode.


Nov 17, 2010 at 12:04 PM // reply »
2 Comments

soory for my message :
your exemple work very well :)
Thank you.


Feb 11, 2011 at 8:01 PM // reply »
272 Comments

@Ben, re: your Oct 30, 2009 at 7:54 AM post:

The sad thing is, over 15 months later, what you said is STILL true. There's still next to nothing on how to use pushStack on api.jquery.com. This article remains the best documentation on it I've been able to find.


Feb 12, 2011 at 11:25 AM // reply »
11,246 Comments

@WebManWalking,

The jQuery documentation in general is really good - part of what makes jQuery such a popular library; I am surprised that this is still a hole in the information. Perhaps they are pushing things like the Widget Factory these days and don't want to encourage people to seek other means of plugin development?


Feb 12, 2011 at 3:37 PM // reply »
272 Comments

@Ben,

I'm about to do something majorly cool with pushStack. Something that's never been done before and allows you to do something that can't be done any other way. When it's done, I'll post an explanation of it here on the same day as plugins.jquery.com.

I'd say what it is, but I don't want to get into a race condition with your readers. :-)


Feb 12, 2011 at 5:03 PM // reply »
11,246 Comments

@WebManWalking,

Ooooh, sounds juicy - looking forward to it.


Feb 14, 2011 at 6:30 PM // reply »
272 Comments

Actually, my plug-in that uses pushStack() is working. But I need to write another plug-in that uses the first one before I release the set.

By the way. I found some documentation of pushStack() in Chaffer/Swedberg' Learning jQuery, June 2007 version, p. 316. This article is much more in-depth, however.


Feb 14, 2011 at 6:31 PM // reply »
272 Comments

Chaffer/Swedberg's


Feb 25, 2011 at 12:31 AM // reply »
272 Comments

@Ben,

Well, I just now released my jQuery plug-ins, 2 of which use .pushStack(). They're part of what I'm calling "The Pseudo-Tables Package".

Release 1.0 page:

http://plugins.jquery.com/content/pseudotablespackage-10

Documentation:

http://www.webmanwalking.org/projects/jquery/jquery.alignPseudoTables/

The 2 plug-ins that use .pushStack() are .findClosest() and .findNestedFirst().

I wrote .findNestedFirst() first. It returns the same elements as .find(), but in most-nested to least-nested order. This allows aligning inner pseudo-tables before the outer ones that contain them. That way, the inner ones will have already been resized, so the alignment of the outer ones will be accurate.

You can think of .findClosest() as being like .closest(), but in the downward direction. So from an outer table, I want JUST the rows it directly contains, JUST the ones associated with the outer table. (I don't want a nested table's rows.) That's the problem with "selector selector" (descendant). There's no way to say "and go no further down the DOM tree".

(Note: I couldn't use "selector > selector" (child) for that purpose, because there could be elements in-between. For example, in a pseudo-table that's being used to align a form, I typically code fieldset between table and rows. So "selector > selector" won't work. I needed a .findClosest() plug-in.)

If you're into reading someone else's code, I think you'll like reading .findNestedFirst(). It recursively builds an ordered tree of found elements to represent the nesting hierarchy. It maintains DOM order in the tree by using arrays of arrays. It also uses recursion to flatten the tree into the single array it returns to .pushStack().

Can you tell I was a computer sciences major? Only computer sciences majors think of practical uses for recursion. :-)


mxn
Mar 4, 2011 at 12:18 AM // reply »
1 Comments

thanks for this plugin...will be using it on my blog...


Apr 26, 2011 at 10:54 AM // reply »
1 Comments

@Ben how's it going brother?!?

Just came across this and sad to admit I just discovered .pushStack() 2 weeks ago. :/

Was sad to see the lack of real documentation, but once again, you're blog has come to my rescue!

Hope all is well!



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
May 24, 2013 at 5:39 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam Oops! My mistake! I hadn't gotten that far in my testing - I'm still baby stepping my way through the process. ... read »
May 24, 2013 at 5:13 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
Hi Jason, Thanks for checking up on that, but I still stand firm on my position. :) There are actually two listLast()'s in use, and you're right that the one using a space as a delimiter is fine. ... read »
May 24, 2013 at 4:45 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Ben I have been lurking your site for quite some time, and haven't stepped up to comment until today. Thanks for all the great info - keep it up! @Adam I believe you are mistaken... as the commen ... read »
May 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools