有什么方法可以检查变量是否是真正的jqXHR? [英] Any way to check whether a variable is a real jqXHR?
问题描述
正如标题已经提到的,有没有办法检查变量是否是真正的jqXHR?
As the title already mentions, is there a way to check whether a variable is a real jqXHR?
我的意思是(想象):
var resource = $.get('/resource');
if (resource instanceof jqXHR)
{
// do something
}
我想解决的实际问题是我正在研究的模态插件。
The actual problem I am trying to solve, is for a modal-plugin I'm working on.
$('#element').modal({
content : function()
{
return $.get('/resource');
}
});
而且,内容
变量可以是 string
或 function
。如果是 string
,它将是静态的,如果 function
它将在每次打开模态时运行。
And, the content
variable can be either string
or function
. In case of string
, it will be static, in case of function
it will be run every time upon opening the modal.
但是,我希望允许内容
回调返回 jqXHR
或 string
。使用字符串非常简单, if(typeof返回==='string')
,但是 jqXHR
?
But, I am looking to allow the content
callback to return either jqXHR
or string
. With string it's pretty simple, if (typeof returned === 'string')
, but what about jqXHR
?
我知道我可以直接检查 string
,如果它不是字符串
,假设它是 jqXHR
,但我希望我的插件尽可能强大,并禁止使用意外类型。
I know that I could simply check for string
and in case it's not a string
, assume it's jqXHR
, but I want my plugin to be as strong as possible, and disallow working with unexpected types.
推荐答案
我建议只检查它是否是一个承诺对象。这将使您的代码更加健壮,因为如果用户需要执行更复杂的操作,用户可以返回自定义延迟对象,或者他们只需返回jqXHR以获得相同的效果。
I suggest just checking whether or not it is a promise object. This will make your code more robust in that the user can return a custom deferred object if they need to do something more complex, or they can simply return the jqXHR for the same effect.
if ($.type(resource) === "string") {
doStuff(resource);
} elseif (resource && resource.promise) {
resource.promise().done(doStuff);
}
这篇关于有什么方法可以检查变量是否是真正的jqXHR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!