Very simple question, thought I could figure this one out but the answer has eluded me.
Is it possible to clear/remove attached handlers to a deferred object done/fail/always queues.
var dfd = $.Deferred()
dfd.done(foo).fail(bar);
// User interacts with the page in a way that I do not want to fire foo or bar
// when dfd is resolved or rejected
<<answer here>>
No, there's no mechanism to remove already-registered callbacks on a $.Deferred()
.
Most times, you only have access to the .promise()
interface of the deferred, and this only allows you to register callbacks and read the promise's state - you cannot modify the promise through any exposed methods.
In your case, you will need those registered callbacks to check some other state variable that is altered by the user interaction, and then have them decide whether to continue or not.
My guess is no, but I won't swear it. You can accomplish at least part (if not all) of what you want without that functionality anyway.
You can always set things up to wait on multiple deferreds with $.when
. So, instead of
var dfd= $.Deferred();
dfd.done(foo).fail(bar);
You'd have
var dfd= $.Deferred();
var userfailedtointeract= $.Deferred();
$.when(dfd,userfailedtointeract).done(foo);
Which you'd resolve userfailedtointeract
after which point it's safe to call foo or reject otherwise
However, this does not take care of conditionally calling bar
, as adding the .fail(bar)
to the above $.when
line means bar
fires when either of the promises are rejected. You only want bar
to fire on failure only if userfailedtointeract
was resolved!
That leads us to the following:
var dfd= $.Deferred();
var userfailedtointeract= $.Deferred();
userfailedtointeract.done(function(){
dfd.done(foo).fail(bar);
});
Which... actually isn't a hard a solution as I thought it would be. But I'm looking at this with insomniac eyes. I might be missing something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With