Using PushStack() In jQuery Plugins To Create New Collections

Posted October 29, 2009 at 9:58 AM

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:

 Launch code in new window » Download code as text file »

  • <!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.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page




Reader Comments

Oct 30, 2009 at 7:44 AM // reply »
10 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 »
7,572 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.


Post Comment  |  Ask Ben

Recent Blog Comments
Lee
Mar 22, 2010 at 10:08 AM
Javascript's Implicit Boolean Conversions
I would certainly still use if(strValue.length > 0) over if(strValue) simply because I believe it makes the code more self-documenting. Not everyone knows that an empty string evaluates to false. ... read »
Mar 22, 2010 at 7:43 AM
Terms Of Service / Privacy Policy Document Generator
Thankyou for this very helpful form. You've made my life much easier today. I'll have a look around your site... I'm sure there's some more good stuff here..Thanks Dave ... read »
Mar 22, 2010 at 7:21 AM
Encountered "(. Incorrect Select Statement, Expecting a 'FROM', But Encountered '(' Instead, A Select Statement Should Have a 'FROM' Construct.
I got this exception now. In case you're using var-es local struct, CF gives you couple of "new" exceptions: Encountered "local. and Encountered "id. Incorrect Select List, Incorrect select colum ... read »
Mar 22, 2010 at 3:08 AM
Ask Ben: Selecting XML Attributes Given Other XML Attributes
Thanks for the response. I finally discovered that I was getting this error because I had cfsetting enablecfoutputonly="yes" in Application.cfc, and was neither setting it to false elsewhere nor brac ... read »
Mar 21, 2010 at 8:57 PM
The Bourne Ultimatum Starring Matt Damon And Julia Stiles
late to the party, but my observation is this: rewatch carefully for the platonic nature of the relationship between nicki and jason. she never flirts with him. he never comes on to her. they alway ... read »
Mar 21, 2010 at 7:40 PM
Is Simulating User-Input Events With jQuery Ever A Good Idea?
A couple of things. One you embed the initial state of of more-info in the CSS. IMHO, that behavior should be in jQuery: moreInfo.hide(); It shows that the behavior your toggling and closing is mor ... read »
Mar 21, 2010 at 3:59 PM
Exploring ColdFusion Component Runtime Class Properties And Serialization
@Elliott, according to Ben's experiment, serializeJSON() doesn't access the private data by default - it doesn't even access the getHair() method - so trying to clone a Girl.cfc via serializeJSON/des ... read »
Mar 21, 2010 at 3:49 PM
Ask Ben: Javascript String Replace Method
I'm confused a bit by what you are asking, but if had this sentence: The color, red, is in the style statement; style: red;. and wanted to remove all or change all of the commas, colons, and semi-c ... read »