[英]Override getJSON and get jQuery promises (done/fail)
I have to override jQuery's getJSON function and am wondering if there is a way to get promise functions (done/fail) inside the override function. 我必须重写jQuery的getJSON函数,并且想知道是否有一种方法可以在重写函数中获取promise函数(完成/失败)。 I would think that the functions are stored somewhere. 我认为这些功能存储在某个地方。 Here is the start of the code: 这是代码的开头:
(function ($) {
$.getJSON = function (url, data, callback) {
this.done = function(){};
this.fail = function(){};
var newDoneFtn = function(response) {
var newData = JSON.parse(response.data);
//call done function here with newData variable
}
var newFailFtn = function() {
//call fail function here
}
newFunction(url, data, newDoneFtn, newFailFtn);
};
})(jQuery);
$.getJSON(someURL, {
id: 1
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('failed');
});
Where I am stuck is trying to get the done and failed functions on the getJSON call to be used with the newFunction. 我陷入困境的地方是尝试在getJSON调用上完成和失败的功能,以与newFunction一起使用。 Please note that I cannot change newFunction. 请注意,我无法更改newFunction。
You should create a new Deferred object using $.Deferred()
. 您应该使用$.Deferred()
创建一个新的Deferred对象。
You can then call / pass its resolve()
and reject()
functions to resolve or fail its promise. 然后,您可以调用/传递其resolve()
和reject()
函数来解决其诺言。
As SLaks already answered; 正如SLaks已经回答的那样; you can return a $.Deferred : 您可以返回$ .Deferred :
function getJson(){
var deferred = $.Deferred();
try{
someCallbackApi(
param
,function(response){
response.error
? deferred.reject(response.error)
: deferred.resolve(JSON.parse(response.data))
}
);
}catch(e){
deferred.reject(e);
}
return deferred.promise();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.