Question

I would like to wrap some jQuery functions (namely ajax) for several reasons, such as global configuration of parameters and, more importantly, being able to exchange it easily.

My question is, how can I "forward" the .done() and .fail() callbacks? (Which design-pattern is responsible for this behavior of jQuery?)

$.ajax({
  url: "http://url.com",
})
  .done(function( data ) {
    // do something
  })
.fail(function() {
    alert( "error" );
  });

For clarification, what I would like to be able to do is writing a function which wraps the above function and behaves like this:

myWrapper({config: "abc"}).done(function( data ) {
    // do something
});
Was it helpful?

Solution

The $.ajax function does return a promise object which offers these methods (done, fail, always, most important then). Just return that object from your myWrapper function.

OTHER TIPS

You need to return the ajax call if you want to do that...

function myWrapper(config) {
    return $.ajax({
        url: "http://url.com",
        data: config
    });
}

and then call like you suggested...

myWrapper({ config: "abc" }).done(function(data) {
    // call is done
});

I've obviously made assumptions in the above code, but it should get the point across clearly enough. If not, just ask :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top