Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to check whether a variable is a real jqXHR?

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.

like image 649
tomsseisums Avatar asked Jan 29 '13 16:01

tomsseisums


1 Answers

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);
} 
like image 199
Kevin B Avatar answered Oct 22 '22 04:10

Kevin B