Wait, what? Well first, duck punching is another name for monkey patching. Monkey Patching is a technique to “extend or modify the runtime code of dynamic languages without altering the original source code.” But then some Ruby hackers decided that since we rely on duck typing so often, a more proper name was in order:
… if it walks like a duck and talks like a duck, it’s a duck, right? So if this duck is not giving you the noise that you want, you’ve got to just punch that duck until it returns what you expect.[1]
In jQuery we can use this to great effect. We’ll employ an AOP-like approach (aspect-oriented programming), maintaining the original function but wrapping it with our enhancement.
Example 1: Adding color support
(This is a silly example, but hopefully it explains the idea. )
You’re fully aware that you can use certain color names in HTML. But sadly, everyone’s favorite Crayola™ color, Burnt Sienna, can’t play along. Well, not until now…
12345678910111213141516
(function($){var_oldcss=$.fn.css;$.fn.css=function(prop,value){if(/^background-?color$/i.test(prop)&&value.toLowerCase()==='burnt sienna'){return_oldcss.call(this,prop,'#EA7E5D');}else{return_oldcss.apply(this,arguments);}};})(jQuery);// and using it...jQuery(document.body).css('backgroundColor','burnt sienna')
Let’s walk through that a little bit slower, shall we?
First we start off with a self-executing anonymous function that makes a happy closure while remapping jQuery to $:
123
(function($){// ...})(jQuery);
Now we save a reference to the old css method as a local variable, and set up our new definition for that method:
Inside our function definition we have an if statement that breaks up two code paths, the new enhanced route, and the old default:
123456789
// if the user passed in backgroundColor and 'burnt sienna'if(/^background-?color$/i.test(prop)&&value.toLowerCase()==='burnt sienna'){// call the old css() method with this hardcoded color valuereturn_oldcss.call(this,prop,'#EA7E5D');}else{// otherwise call the old guy normally, taking his return value and passing it on.return_oldcss.apply(this,arguments);}
Scroll back up to see the whole thing together. Can you dig it?
Example 2: $.unique() enhancement
$.unique only winnows an array of DOM elements to contain no duplicates, but what if you want all non-duplicates of any type? Here’s an upgrade:
123456789101112131415161718192021222324
(function($){var_old=$.unique;$.unique=function(arr){// do the default behavior only if we got an array of elementsif(!!arr[0].nodeType){return_old.apply(this,arguments);}else{// reduce the array to contain no dupes via grep/inArrayreturn$.grep(arr,function(v,k){return$.inArray(v,arr)===k;});}};})(jQuery);// in use..vararr=['first',7,true,2,7,true,'last','last'];$.unique(arr);// ["first", 7, true, 2, "last"]vararr=[1,2,3,4,5,4,3,2,1];$.unique(arr);// [1, 2, 3, 4, 5]
A Duck Punching Pattern
Here’s the bare pattern. Feel free to use this as the basis of your own:
1234567891011121314
(function($){// store original reference to the methodvar_old=$.fn.method;$.fn.method=function(arg1,arg2){if(...condition...){return....}else{// do the defaultreturn_old.apply(this,arguments);}};})(jQuery);
What else could I use this for?
Some other uses I’ve had or seen for this sort of thing:
Since the release of 1.4, there’s been a lot of discussion about live(). Now that it’s almost as fully featured as bind(), it’s getting quite a workout.
One of the larger calls to action is to introduce $.live(selector,eventType,handler). There are two primary reasons I’ve seen behind this proposal:
There is a performance hit for the initial selection in $('a.whatever').live(.. that isn’t neccessary
live() cannot work on any arbitrary collection of DOM elements in jQuery object, as a side effect of a very different internal operation, thus providing an inconsistent developer experience than all other $.fn.foo methods.
I do not think the performance gain in $.live is worth adding it to jQuery core, by any means. Let’s take an example.
Let’s say we’re dealing with $(selector).live('click',fn)
On every click on the page, the event is caught at the context.. the document. But evt.target points to the top-most element that was clicked on.
jQuery then traverses from evt.target through each ancestor of that node all the way up to document checking if (jQuery(elem).is(selector)).[source]
I think a reasonable estimated depth of evt.targets is like 8 (From the document to HTML element to BODY and so on.. a depth of 20 is not uncommon by any means). And lets say we have an average 5 clicks on a page.
That’s 40 total checks against the selector (plus the original one done at bind time).
So in my opinion a 1/41 speed gain isn’t worth changing the API.
Scoping the delegation a context, however has a much larger impact on performance: $(selector,elem).live('click',fn) Here, only clicks within the context are caught, so not only is the parent traversal depth much more shallow, but that entire sequence is avoided for all events occurring outside that area.
The current API to take advantage of this optimization requires code like $('a.awesome', $('#box')[0]).live(... Yuck! So I wrote a patch to deliver this same optimization to any ID-rooted selectors. (The perk being that everyone who learns #id-rooted selectors are fast for selecting get a related perf boost here). But as Justin Meyer pointed out in the comments, it’s not as flexible as live() currently is.
$.fn.live cannot operate on any jQuery-wrapped collection of elements
Quite simply, $.fn.live needs to be at the top of a chain to guarantee the .selector and .context properties of the jQuery object represent that set. Unlike other $.fn methods, live utilizes those properties and not the actual collection of elements that result from selection, traversing, and filtering.
$.live() and let $.die()
What are the possible solutions?
Turn on a dirty flag in traversal methods, so if you try and live() that collection, it will throw an error.
Deprecate $.fn.live and use $.live(selector[,context],type,handler)
Use $.live to create a “live jQuery object” that defaults to live-bindings: $.live(selector,context).click(fn).mouseenter(fn).unbind("click")[source]
Change $.fn.live to operate from a context:$(context).live('selector', event, fn) This bakes the performance benefit from above right in.
Any others? What do you guys think? Is there a solution that preserves backwards-compatibility while solving the issue?
btw- thx to jmar777, yehuda katz, ben alman, ajpiano, brandon aaron and julian aubourg for their great thoughts on the issue.
The people in this discussion got together and hashed out what would make sense. John Resig then landed a new delegate/undelegate API. It’s good. :)