Ask Ben: Overriding Core jQuery Methods

Posted June 30, 2009 at 2:06 PM

Tags: Javascript / DHTML, Ask Ben

Is there a way to overload the included remove() function in jquery? Possibly a separate js file? For example we are using the min version and it would be cool to not have to add this in each time we upgraded to a new version that has come out?

jQuery is such a well thought out, powerful Javascript library, that it actually uses itself to build itself. What I mean by that is that many of the methods provided by the jQuery library are actually built internally as plugins to the jQuery architecture. When you start to think about the methods in this way, it is a small leap to see that we can override a given jQuery method by simply creating a new plugin of the same name.

 
 
 
 
 
 
 
 
 
 

Before I demonstrate this, I want to just prefix this with saying that by overriding a core library method, you do run the risk of creating problems when upgrading the library. If you override a method and then don't update it in parallel with the library updates, you might retain bugs that subsequent releases of the library have fixed. That said, in the following demonstration, I am going to override the remove() method by creating a new "remove" plugin:

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

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>Overriding jQuery Methods</title>
  • <script type="text/javascript" src="jquery-1.3.2.js"></script>
  • <script type="text/javascript">
  •  
  • // Create a closure so that we can define intermediary
  • // method pointers that don't collide with other items
  • // in the global name space.
  • (function(){
  • // Store a reference to the original remove method.
  • var originalRemoveMethod = jQuery.fn.remove;
  •  
  • // Define overriding method.
  • jQuery.fn.remove = function(){
  • // Log the fact that we are calling our override.
  • console.log( "Override method" );
  •  
  • // Execute the original method.
  • originalRemoveMethod.apply( this, arguments );
  • }
  • })();
  •  
  •  
  • // When DOM is ready, initialize.
  • $(function(){
  •  
  • $( "a" )
  • .attr( "href", "javascript:void( 0 )" )
  • .click(
  • function(){
  • // Remove the target link.
  • $( this ).remove();
  •  
  • // Cancel default event.
  • return( false );
  • }
  • )
  • ;
  •  
  • });
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Override a jQuery Method
  • </h1>
  •  
  • <p>
  • <a>Remove Me 1</a>
  • <a>Remove Me 2</a>
  • <a>Remove Me 3</a>
  • </p>
  •  
  • </body>
  • </html>

In the above code, we are creating our new "remove" plugin inside of its own closure. This is done so that we can create an intermediary variable - a reference to the original remove() plugin - without colliding with other variables in the global name space. Once we have this pointer, we then override the core remove() method with our new jQuery.fn.remove method. For testing purposes, we are simply logging a note that we are in the new method and then executing the original method.

Of course, if you wanted to override the core version, you wouldn't turn around and call apply() on it - you'd actually move the original remove() logic into our new plugin and then update it as necessary. In this way, you can fully override the core method with whatever logic you see fit. I hope this helps.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page




Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Jun 30, 2009 at 7:21 PM // reply »
15 Comments

Nice. Pretty nice Ben.


Jul 1, 2009 at 8:13 AM // reply »
6,371 Comments

@William,

Thanks my man. I've never actually done this in production, but it seems straightforward enough.


Jul 1, 2009 at 10:31 AM // reply »
20 Comments

That's pretty cool. You can even take it a step further and just use a copy of the original jQuery function object to be able to replace multiple functions all at once. I borrowed the clone function from here, http://my.opera.com/GreyWyvern/blog/show.dml/1725165. Then I used it to make a copy of jQuery's functions so that I can call any of the original methods in my new extended version.

Object.prototype.cloneObject = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'cloneObject') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].cloneObject ();
} else newObj[i] = this[i]
} return newObj;
};

(function(){
// Store a reference to the original remove method.
var SuperJQ = jQuery.fn.cloneObject();

// Define overriding method.
jQuery.fn.extend({
remove: function(){
// Log the fact that we are calling our override.
console.log( "Override Remove method" );

// Execute the original method.
return SuperJQ.remove.apply( this, arguments );
},
parent: function() {

// Log the fact that we are calling our override.
console.log( "Override Parent method" );

// Execute the original method.
return SuperJQ.parent.apply( this, arguments );

}
})
})();


Jul 3, 2009 at 9:02 AM // reply »
6,371 Comments

@Anthony,

Nice suggestion. Using the extend() method is definitely a quality choice, especially if you have more than one method to set / override at a given time.


Sep 16, 2009 at 1:50 PM // reply »
1 Comments

thanks, this was very useful to me.

Additionally, I will add. (This has nothing to do with your post but relates to my specific situation)

if someone is trying to apply a override for a specific situation
and needs to compare objects, it wont work. (in jQuery)

Apparently jQuery Objects are 'never' identical. (even if they appear to be)

e.g this:
if (this === jQuery('td#elem_pager')){ // will never evaluate to true

// or this of course
if (this == jQuery('td#elem_pager')){ // will never evaluate to true

One will need to use an attribute (or something) such as:

if (this.attr('id') == jQuery('td#elem_pager').attr('id')){ //can evaluate to true
// override core method, re: cant modify 3rd party libs
apply_specific_functionality;
}
else {
// Execute the original method.
originalRemoveMethod.apply( this, arguments );
}

I apologize if this is obvious/rudimentary info, please correct me
if it is incorrect as well.

I also realize this is not good approach as it's not really scalable,
however it will work in my situation for now


Sep 21, 2009 at 8:23 AM // reply »
6,371 Comments

@Dwright,

Interesting. I have never tried to compare two jQuery objects, but I guess that makes sense since a new jQuery object is created for each selector.


Post Comment  |  Ask Ben

Recent Blog Comments
Jill
Nov 7, 2009 at 11:40 AM
How To Unformat Your Code (Like A Pro)
Derek, I think you might be right - sweet! Thanks for the link :) ... read »
Nov 7, 2009 at 11:25 AM
How To Unformat Your Code (Like A Pro)
I think it would be way easier to just use this http://www.logichammer.com/html-formatter/ He just released v3 and it rocks. ... read »
Jill
Nov 7, 2009 at 7:58 AM
How To Unformat Your Code (Like A Pro)
LMAO - this was pretty funny! I have to admit - I also love to reformat code so I can read it. My boss used to tell me to leave my OCD at home. Now I don't feel so bad after reading everyone else' ... read »
Nov 6, 2009 at 10:10 PM
How To Unformat Your Code (Like A Pro)
The timing of this post is just uncanny. I spent the last 15-20 minutes manually un-formatting my "Ben Nadel" style code within a CFC of mine. I was really digging the readability a few weeks ago, bu ... read »
Roe
Nov 6, 2009 at 5:11 PM
Passing Arrays By Reference In ColdFusion - SWEEET!
ArraySort also reorders the results of these java obj's ... read »
Nov 6, 2009 at 4:53 PM
How To Unformat Your Code (Like A Pro)
I tried to go *back* the other way. Adding formatting is actually a much more complicated problem than removing formatting. Anyway, here is what I could put together with a minimal amount of time: ... read »
Asaf
Nov 6, 2009 at 2:35 PM
ColdFusion GetPageContext() Massive Exploration
Hi, I actually found this post useful. I recently acquired a SSL certificate for my website and when I switched over to HTTPS Internet Explorer would throw an error when trying to download a dynamic ... read »
Nov 6, 2009 at 2:19 PM
How To Unformat Your Code (Like A Pro)
@Chuck, @Nathan, Well, now I feel like it's a challenge.... I accept. ... read »