Last active
September 29, 2015 17:48
-
-
Save danheberden/1641098 to your computer and use it in GitHub Desktop.
mock ajax for the jqueries
This file contains 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
// 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