質問

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