Skip to content

Instantly share code, notes, and snippets.

@ironboy
Created September 14, 2012 11:54
Show Gist options
  • Save ironboy/3721518 to your computer and use it in GitHub Desktop.
Save ironboy/3721518 to your computer and use it in GitHub Desktop.
Jquery ajax dummy responses, to remove need to wait for backend implementation...
(function($){
/*
ajaxDummyResponse.js
TF 2012
Let frontenders using jquery play around with dummy ajax responses
instead of waiting for backenders in an easy way...
Please Note: First discuss, agree on and document an API...
so that the bridge will meet at the middle when you remove the dummies
*/
/* Usage:
Register a dummy like so:
$.ajax.dummy(condition,function);
where condition is a string like 'url == 'backend.php" && data.action == "fetch"'
and func is a function that will recieve the jquery ajax settings object
Make your ajax call:
$.ajax({url: 'backend.php', data: {action: 'fetch'}, success: function(){doSomething()});
if the call matches a dummy condition then the dummy function will answer it
by ignoring server communication and sending its function result to the success method
*/
var dummyMem = [], realAjax = $.ajax;
$.ajax = function(a){
for(var i = 0; i < dummyMem.length; i++){
if(dummyMem[i].condition(a)){
(function(){
var func = dummyMem[i].func, obj = a;
setTimeout(function(){
if(!obj.success){return;}
obj.success.apply(obj,[func(obj)])
},1);
})();
return;
}
}
return realAjax.apply($,[a]);
};
$.ajax.dummy = function(condition,func){
var condFunc;
eval('condFunc=function(d){with(d){return ' + condition + '}}');
dummyMem.push({condition:condFunc,func:func});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment