10

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.

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • 2
    You can check it's properties, for example, if it has done, fail, responseText, promise, and abort methods, you can be pretty sure that it is a jqXHR object. However, all you really care about is whether or not it is a promise object so that you can use .done and .fail. Just test for the `promise` method being defined on it. – Kevin B Jan 29 '13 at 16:23
  • possible duplicate of [How can I determine if a jQuery object is deferred?](http://stackoverflow.com/questions/10965065/how-can-i-determine-if-a-jquery-object-is-deferred) – Ian Jan 29 '13 at 16:27

1 Answers1

6

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);
} 
Kevin B
  • 94,570
  • 16
  • 163
  • 180