Archive

Posts Tagged ‘BrisJS’

Duck Punching

March 6, 2012 1 comment

duck punch

… 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.

 

Last night at BrisJS I gave an impromptu lightning talk on the concept of Duck Punching.

And no, I am not going around beating up poor little duckies…

 

Run Ducks Run

 

I’ll show here the brief example I spoke about last night, as I did a very quick overview without explaining it much, but for some better examples and some more info check out this post from Paul Irish.

 

Duck punching also know as Monkey Patching. is an approach to extend or modify the runtime code of dynamic languages (such as JavaScript) without altering the original source code.

So for example I am sure everyone is aware of the jQuery function “toDuck()” and the current bug where the duck says the wrong thing…

jQuery.fn.toDuck= function(){
        this.text("The duck says: Moo!")
    };

On our site we want to use this function to show some ducks.

<div>Hello World</div>
<button>Make it a duck!</button>​
$('button').on('click', function() {
    
    $('div').toDuck();
    
});

Result:

 The duck says: Moo! 

 

OK so we want to change the functionality / fix this bug but we don’t want to go edit the original source as its minified, will make it harder to take upgrades, etc. To achieve this then we can use duck punching to “enhance” this functionality.

 

(function($) {

    // store original reference to the method
    var orig = $.fn.toDuck;

    $.fn.toDuck = function() {
   
        // Do original function
        orig.apply(this,arguments);
            
        if (this.text() === 'The duck says: Moo!') {
            this.append("  *Punch*  Woof!  *Punch* *Punch*  Quack?... *Gives Ducky bread*");
        }
        
    };
}(jQuery));

 

And our new result:

 The duck says: Moo! *Punch* Woof! *Punch* *Punch* Quack?... *Gives Ducky bread* 

 

As you can see the original functionality remains untouched but we get our desired quack.

Should the original method be fixed down the track our condition will fail and the additional functionally will not be run.

This very strange and contrived example can be on jsFiddle here.

 

Categories: JavaScript, Presentations Tags: ,