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
});
有帮助吗?

解决方案

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.

其他提示

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 :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top