views:

163

answers:

1

If I want to tweak some of the capability of a jQuery UI object, by replacing one of the functions, how would I go about doing that?

Example: suppose I wanted to modify the way the jQuery autocomplete widget rendered the suggestions. There's a method on the autocomplete object that looks like this:

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "</a>" )
        .appendTo( ul );
},

Could I replace this?

I think this might be called Monkey Patching.

How? What syntax would I use?

+3  A: 

I don't know about jQuery UI, but in general, this is how you redefine a function:

(function() {
   var _oldFunc = _renderItem;

   _renderItem = function(ul,item) {
      // do your thing
      // and optionally call the original function:
      return _oldFunc(ul,item);
   }
})();

The reason this is wrapped in an anonymous function is to create a closure for storing the original function. This way it can never interfere with global variables.


EDIT
To do this to a fn on a jQuery UI widget, use this syntax:

FYI: the way to grab the function is like this:

function monkeyPatchAutocomplete() { 

  // don't really need this, but in case I did, I could store it and chain 
  var oldFn = $.ui.autocomplete.prototype._renderItem; 

  $.ui.autocomplete.prototype._renderItem = function( ul, item) { 
     // whatever
  }; 
} 
Philippe Leybaert
monkey patching or, as Paul Irish explains, duck punching :) - http://paulirish.com/2010/duck-punching-with-jquery/
Russ Cam
I get that part - the thing I am having trouble with is the jQuery-esque part. The way jQuery UI defines widgets and so on.
Cheeso
Have you read the UI Developer Guide? - http://jqueryui.com/docs/Developer_Guide
Russ Cam
Nope! I didn't know there was such a thing.
Cheeso