Skip to content

Instantly share code, notes, and snippets.

@danheberden
Last active September 29, 2015 17:48
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 danheberden/1641098 to your computer and use it in GitHub Desktop.
Save danheberden/1641098 to your computer and use it in GitHub Desktop.
mock ajax for the jqueries
// Mojax
// Copyright (c) 2011 Dan Heberden
// Dual licensed under the MIT and GPL A
var randomStrings = [ "Joe", "Bill", "Steve", "Mark", "Joanne", "Megan", "Kristy", "Suzie" ];
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
if ( /^\/?mock-ajax/.test( originalOptions.url ) ) {
// make new deferred and save any success/error handlers
var dfd = new $.Deferred(),
success = options.success,
error = options.error;
// kill off the old handlers
options.success = options.error = null;
// map these promise methods onto the jqXHR
dfd.promise( jqXHR );
// simulate success and error
dfd.done( function() {
success && success.apply( options, arguments );
});
dfd.fail( function(a,b,c) {
error && error.apply( options, arguments );
});
var echo = originalOptions.data.echo || {},
delay = originalOptions.data.delay || .05,
status = originalOptions.data.status || true;
if ( originalOptions.data.random ) {
echo = randomStrings[ ~~(Math.random()*randomStrings.length) ];
}
// resolve the data
setTimeout( function() {
dfd[ status ? 'resolve' : 'reject' ]( echo, 'success', jqXHR );
}, delay * 1000 );
// abort out of this function, so the
// promise still gets returned via $.ajax
setTimeout(function(){
jqXHR.abort( 'success' );
},0);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment