Is it possible to add methods to JQuery's promise object?

后端 未结 3 1202
萌比男神i
萌比男神i 2021-01-17 02:23

I want to add a catch method to JQuery\'s promise object so I don\'t have to type the following every time:

.then(null,function(dat         


        
3条回答
  •  庸人自扰
    2021-01-17 03:07

    Yes, it is possible, but I would strongly recommend not to do this. Rather use a proper promise library and assimilate your jQuery promises; so that you can use the libraries builtin (and correct) .catch() method - so that you can omit that return $.Deferred().resolve().promise(); line as well.

    The problem with extending jQuery promises is that they don't inherit from a prototype which we could simply amend, but use a factory pattern (read the source). You'll need to decorate it:

    jQuery.Deferred = (function($Deferred) {
        var Deferred = function(func) {
            var deferred = $Deferred(func),
                promise = deferred.promise();
            deferred.catch = promise.catch = function(fnFail) {
                return promise.then(null, fnFail);
            };
            return deferred;
        };
        return Deferred;
    }(jQuery.Deferred));
    

提交回复
热议问题