HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Return fake jqXHR from custom Ajax method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ajaxmethodreturncustomfromjqxhrfake

Problem

I have several methods that wrap the $.ajax() method and return its jqXHR, but I need to force fail before even calling the original $.ajax() and still allow to use success/error methods of the result.

//just a very simple example, actuall code is more complicated
$.rpc = function(method, args) {

    if (!method || 'string' === typeof method ||) {
        return false; //PROBLEM - cannot use success/error handlers!
    }

    return $.ajax({
        type: 'POST',
        url: '/rpc',
        data: { method: method, params: args },
    }); //AJAX()
};

//usage:
$.rpc(loginMethod, credentials).success(gotoProfile).fail(gotoLogin);
//if loginMethod is for any reason undefined it crash instead of calling fail handler


So I use this helper method, since the jqXHR is created directly inside the Ajax method:

$.ajax.getFailed = function(message) {
    var
        jqDef = new $.Deferred(),
        jqXHR = jqDef.promise();

    jqXHR.success = jqXHR.done; //deprecated  $.ajax methods
    jqXHR.error = jqXHR.fail;

    jqDef.reject.defer(1, jqXHR, [jqXHR, message]);
               //defer is from extJS, alternative to setTimeout

    return jqXHR;
};

$.rpc = function(method, args) {

    if (!method || 'string' === typeof method ||) {
        return $.ajax.getFailed('Missing method');
    }

    return $.ajax({
        type: 'POST',
        url: '/rpc',
        data: { method: method, params: args },
    }); //AJAX()
};


Is this code OK or is there anything else I should add?

Solution

Looking at the documentation for $.ajax reveals a beforeSend option that would allow you to cancel the request before it's sent by returning false.

$.rpc = function(method, args) {
    var beforeSend = function () {
        return method && 'string' !== typeof method;        
    }

    return $.ajax({
        type: 'POST',
        url: '/rpc',
        data: { method: method, params: args },
        beforeSend: beforeSend
    }); 
};

Code Snippets

$.rpc = function(method, args) {
    var beforeSend = function () {
        return method && 'string' !== typeof method;        
    }

    return $.ajax({
        type: 'POST',
        url: '/rpc',
        data: { method: method, params: args },
        beforeSend: beforeSend
    }); 
};

Context

StackExchange Code Review Q#83837, answer score: 2

Revisions (0)

No revisions yet.