Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear/Remove attached handlers to $.Deferred Objects

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>>
like image 382
Frzy Avatar asked Oct 24 '13 08:10

Frzy


2 Answers

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.

like image 129
Alnitak Avatar answered Nov 18 '22 07:11

Alnitak


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.

like image 2
JayC Avatar answered Nov 18 '22 09:11

JayC