1

I am looking for a way to expand an existing Jquery function to give it more options/parameters.

The one I want to use is $.ajax but this could apply to any jquery function.

I want to be able to call a function like this:

$.adv_ajax()

Which would be an extended version of the $.ajax function like as follows:

 $.adv_ajax({
  custom_parameter: "abc", //my custom one
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});
Petty_Crim
  • 431
  • 1
  • 5
  • 14

2 Answers2

8

Something like this:


(function($)
{
    // maintain a to the existing function
    var oldAjax = $.ajax;
    // ...before overwriting the jQuery extension point
    $.fn.ajax = function()
    {
        // original behavior - use function.apply to preserve context
        var ret = oldAjax.apply(this, arguments);


        // preserve return value (probably the jQuery object...)
        return ret;
    };
})(jQuery);


Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • +1 for showing how to change an existing function and good jQuery coding practise. But it is probably $.ajax not $.fn.ajax that should be changed. Also might be an overkill for this question as the op wants to create a function with a different name. – Daff Jan 10 '12 at 05:27
  • I want to extend it, so I am looking for the best way to do that. However I do not want to overwite .ajax in any way just extend it. – Petty_Crim Jan 10 '12 at 05:39
3

Well then just attach your function to the jQuery object:

$.adv_ajax = function(options) {
    // Do stuff like change some options and then call the original
    return $.ajax(options);
}
Daff
  • 43,734
  • 9
  • 106
  • 120