Is it possible to reset a jQuery deferred object state?

后端 未结 3 1638
终归单人心
终归单人心 2021-01-11 09:39

Is it possible to reset a resolved jQuery object to an \'unresolved\' state and kick off it\'s initialization and callbacks all over again?

The specific thing I\'m d

相关标签:
3条回答
  • 2021-01-11 09:46

    No. A Promise is by definition a thing that resolves only once - from unresolved to fulfilled OR to rejected. You will not be able to do this with jQuery's Deferreds.

    What you are actually searching for are Signals. They are to be fired more than once, but provide a similiar interface. There are some implementations around, you might ceck out js-signals or wire.js.

    0 讨论(0)
  • 2021-01-11 09:47

    The only solution I could find is to reset the $.Deferred object and return new Promise from that one. It works together with some internal API dirty checking (if something gets edited / deleted), but would be more performant to just reset the existing $.Deferred and let it re-resolve on the next Promise request.

    0 讨论(0)
  • 2021-01-11 10:07

    An example of a possible solution is:

    $.myDeferredList = [];
    $.createRestorableDeferred = function(a,b) {
        // JUST BY SIMPLE $.when().then();
        $.myDeferredList[a] = {
            deferred: $.Deferred()
            , then: b
            ,restore : function() {
                $.myDeferredList['myReady'].deferred = $.Deferred();
                $.when($.myDeferredList['myReady'].deferred).then($.myDeferredList['myReady'].then);
            }
            ,resolve : function() {
                $.myDeferredList['myReady'].deferred.resolve();
            }
        }
        $.when($.myDeferredList['myReady'].deferred).then($.myDeferredList['myReady'].then);
        window[a] = $.myDeferredList['myReady'];
    }
    
     var counter = 0;
     $.createRestorableDeferred('myReady', function () {
         console.log('>> myReady WHEN called',++counter);
         $.myDeferredList['myReady'].restore();
    
     });
    
    // RESOLVING ways
    
    $.myDeferredList['myReady'].deferred.resolve();
    $.myDeferredList.myReady.deferred.resolve();
    myReady.resolve();
    

    Results in console:

     >> myReady WHEN called 1
    
     >> myReady WHEN called 2
    
     >> myReady WHEN called 3
    
    0 讨论(0)
提交回复
热议问题