Created
May 9, 2011 23:53
-
-
Save quickredfox/963664 to your computer and use it in GitHub Desktop.
$.ajax bitchslap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
$.ajax Bitchslap! | |
================= | |
$.ajax Bitchslap! $.ajax is a bein' a bitch and I promise I'll slap it! | |
Sometimes you need to code and move on until the world fixes itself or declares it wont fix itself. | |
This is one example of temporarily working around that. | |
It says in the jquery documentation that $.ajax returns a promise, but that appears to not | |
be true for some cases. Dont believe me? Look at the jQuery source where deferreds are being | |
attached in $.ajax, correct me if I'm wrong but there's stuff like | |
if ( state === 2 ) { | |
return false; | |
} | |
and that's not really a Deferred is it? | |
I ran accross this while attempting the likes of: | |
request = $.ajax( { url: ..., beforeSend(){ if(!conditon) return false }}) | |
request.then( doneCallback, failCallback ) | |
It works if condition passes but if condition fails (if let's say you have a $.ajaxPrefilter) | |
request.then throws and error and is in fact "false" and last time i checked a boolean, | |
is not a promise. | |
*/ | |
(function(jQueryAjax) { | |
function isPromise( obj ) { | |
return obj.then && typeof obj.then === 'function' | |
}; | |
$.ajax = function( url, settings ) { | |
var output,response = $.Deferred(),settings = settings||{} | |
if( typeof url === 'string') settings.url = url; | |
else settings = ( typeof url === 'object' ? url : {} ); | |
output = jQueryAjax.apply( settings.context||settings, arguments ) | |
if( isPromise( output ) ){ | |
return output | |
}else if( output === false ){ | |
response.reject( 'ajax returned a false promise' ) // ;) | |
}else{ | |
response.reject( 'ajax did not return a promise' ) | |
} | |
return response.promise() | |
}; | |
})($.ajax); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didnt actually use this, the solution was to forget using my ajaxPrefilter strategy and write some functions that wrap $.ajax call handling instead. sort of what you see here, but purpose-specific.