-->

Propagating events between JQuery.Deferred objects

2019-06-26 12:05发布

问题:

How can I propagate all events on one JQuery.Deferred() object to another ?

Is there a better / simpler / shorter way then handling both .fail and .then .done by calling the other objects .rejectWith and .resolveWith ? I am assuming that I don't have to handle .done .then as it will be called when I call Reject or resolve.

I suspect that maybe this can be done using .pipe but I am not sure how.

UPDATE:

Note: I also I fixed some of the text above per @Frédéric Hamidi's comment.

What I am trying to achieve was the following:

I had a API that was making ajax calls to the server, they would return the ajax object (which is a $.Deferred itself).

At some point I needed to handle a situation where I had not net work available (This is for a phonegap application running on a mobile device).

What I wanted to do was that in case of no network connectivity I would display a dialog prompting the user to fix the network issue and hit "retry".

But in this scenario I would not call the $.ajax until the user hits retry so I did not have a $.Defferred object to return the the function that called on the API to begin with.

so I ended up understanding that I could just create a new $.Defferred and return it and on the callback for the retry button call the $.ajax itself setting it to "relay"/propagate the defferred events to the one I just returned by holing it as part of a closure.

But I was not sure of the way to do it. My mixup with the the .pipe method is because its description says its a:

Utility method to filter and/or chain Deferreds.

I hoep this makes my Question more clear.

回答1:

If I understand correctly, you just want a Deferred to resolve/reject and notify with the exact same value as your ajax request? If so, assuming your Deferred object is called defer, the following code will do the trick:

$.ajax( ... ).done( defer.resolve ).fail( defer.reject ).progress( defer.notify );

It works because defer.resolve, defer.reject and defer.notify are lexically bound: the context (this) and values (arguments) are passed properly so you just effectively forwarded the state of the ajax promise into the new deferred.



回答2:

If you have 2 deferred objects, d1 and d2, you can propagate from d2 to d1 with: d2.then(d1.resolve,d1.reject,d1.notify)

An example: http://jsfiddle.net/bgrossi/XTJEf/