是否可以向JQuery的Promise对象添加方法? [英] Is it possible to add methods to JQuery's promise object?
问题描述
我想向JQuery的promise
对象添加catch
方法,因此我不必每次都键入以下内容:
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(data){
// handle error
return $.Deferred().resolve().promise();
});
此外,它将使阅读变得更容易.我将如何在JQuery 1.11中做到这一点?
Also, it'll make it easier to read. How would I do this in JQuery 1.11?
推荐答案
是的,可以,但是我强烈建议您不要这样做.而是使用适当的Promise库并吸收您的jQuery Promise;这样您就可以使用内置的库(并且是正确的).catch()
方法-这样就可以省略return $.Deferred().resolve().promise();
行.
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.
扩展jQuery Promise的问题在于它们不继承我们可以简单修改的原型,而是使用工厂模式(请阅读装饰它:
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));
这篇关于是否可以向JQuery的Promise对象添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!