skip to Main Content

How do I delete a previously assigned handler?

var deferred = $.Deferred();

var callback = function(n) {
    console.log('Test ' +n);
}

deferred.progress(callback);

deferred.notify(1);

$(deferred).off('progress', callback); // It doesn't work =(

deferred.notify(2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Is there a way built into jQuery to remove jQuery.Deferred handlers?

2

Answers


  1. Chosen as BEST ANSWER

    I found out that jQuery.Deferred uses jQuery.Callbacks. This allowed us to write a wrapper for jQuery.Deferred and pull the ability to manage handlers to the top. Below is an example.

    (function() {
        
        var deferred_original = jQuery.Deferred;
        
        jQuery.Deferred = function() {
            
            var callbacks = [];
            
            var callbacks_original = jQuery.Callbacks;
            
            jQuery.Callbacks = function() {
                var callback = callbacks_original.apply(this, arguments);
                callbacks.push(callback);
                return callback;
            }
            
            var deferred = deferred_original.apply(this, arguments);
            deferred.callbacks = jQuery(callbacks);
            
            jQuery.Callbacks = callbacks_original;
            
            return deferred;
            
        }
        
    })();
    
    // Test:
    
    var deferred = $.Deferred();
    
    var callback = function(n) {
        console.log('Test ' +n);
    }
    
    deferred.progress(callback);
    
    deferred.notify(1);
    
    // This will remove the progress handler:
    deferred.callbacks.each(function(n, c) { c.remove(callback); });
    
    deferred.notify(2);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


  2. No, there’s no function to remove already-registered callbacks on a $.Deferred().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search