Luke Madhanga
Luke Madhanga

Reputation: 7467

How to extend jQuery's AJAX function

I've played around with creating my own jquery functions, this done via the

$.fn.extend({
    myFunc: function () {

    }
});

However, after scouring the web and SO for an answer, I would like to ask:

How can I extend $.ajax()

The new implementation of $.ajax can be used by running

$.ajax({

}).done(function (e) {

}).fail(function (e) {

});

What I would like to do is to add a .progress() so that I don't always have to write

$.ajax({
    url: path,
    xhrFields: {
        onprogress: function (e) {
            if (e.lengthComputable) {
                console.log(e.loaded /e.total * 100 + '%');
            }
        }
    }
});

each time I want to monitor the progress. e.g.

$.ajax({
    url: '/somewhereorother',
    type: 'post',
    dataType: 'json'
}).progress(function (e) {
    updateProgressBar(e.percentage + '%');
}).done(function (e) {

}).fail(function (e) {

});

Upvotes: 1

Views: 3140

Answers (1)

eithed
eithed

Reputation: 4339

$.ajax is a function attached to $ object.

As such, to extend it you would have to store the reference to it somewhere, and call it when needed, something like:

var ajax = $.ajax;
$.ajax = function()
{
     if (!arguments[0].success)
     arguments[0].success = function()
     {
          window.alert('done!');
     }

     ajax.apply(ajax, arguments);
}

This is a concept (I'm not sure of this scope in apply - would have to actually run it) ;) Also, I'd say it's ugly as hell way of doing things.

If you want your $.ajax function to differ from official function, I'd still separate it. Either via $.my_ajax or by separate namespace (take a look at http://api.jquery.com/jquery.sub/)

Upvotes: 1

Related Questions