As the title already mentions, is there a way to check whether a variable is a real jqXHR?
I mean (imaginary):
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');
}
});
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.
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
?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With