Skip to content

Instantly share code, notes, and snippets.

@markelog
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markelog/5a5aec471886a863a136 to your computer and use it in GitHub Desktop.
Save markelog/5a5aec471886a863a136 to your computer and use it in GitHub Desktop.
jQuery.xhr
// jQuery made popular chaining style in JavaScript,
// as i recall this approach we liked at San Diego meeting,
// i think we could use similar approach for $.xhr
//
// also https://github.com/visionmedia/superagent
$.xhr( "url" )
// Default method is GET
.method( "post" )
.timeout( 1000 )
.cache( false|true )
// Expose native xhr, basically just like beforeSend of jQuery.ajax
.native(function( xhr ) {
xhr.setRequestHeader( "X-Hippo", "happy" );
})
// Would like to note – these methods:
.username(...).password(...)
// should not be provided with jQuery.xhr.
// User should use Authorization header or we could provide an option
// to include these methods in the build, but not by default
// Since this is a common use-case, so it should be used pretty often
.header( "X-Hippo", "happy" )
// Only at this moment send data to the server
.send({ data: "data" })
// These next three methods are not promise methods, just callbacks aggregators
.callback|complete(function( error, xhr ) {
...
})
// I realize that common opinion is not deal with 5xx and 4xx ourselfs
// But i feel it would be nice to do so than introduce $.xhr.toSuccessError method
.success(function( xhr ) {
...
})
.fail(function( error, xhr ) {
...
})
// By default return Deferred, if included in the build, otherwise noop
// This will provide nice symmetry with http://api.jquery.com/promise/
.promise().then().done().fail().etc();
// but if
.promise( window.Promise ).then().catch() // use native promise
// Or any other promise,
// but that promise implementation should be compatable with ES6 promises –
.promise( Bluebird ).then().error().spread().etc()
.promise( vow.Promise ).whatever()
// Pass only xhr object to then method
.then( $.xhr.as( "contentType" ) )
// or
.then( $.xhr.as( "json" ) )
// Also we could provide helper with reverse logic of $.xhr.toSuccessError
.then( $.xhr.strictError )
// Do not do this or something like:
$.xhr.convertors = {
json: function( error, xhr ) {
return jQuery.parseJSON( xhr.responseText );
},
// json, contentType, etc
};
// All those methods should be private
// If this concept is acceptable, we should provide similar interface for other
// transports i.e. jsonp and script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment