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?
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>