Skip to content

Instantly share code, notes, and snippets.

@ifandelse
Created November 25, 2011 06:50
Show Gist options
  • Save ifandelse/1392960 to your computer and use it in GitHub Desktop.
Save ifandelse/1392960 to your computer and use it in GitHub Desktop.
Traffic Cop Source
/*
TrafficCop
Author: Jim Cowart
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
Version 0.1.0
*/
(function($, undefined) {
var inProgress = {};
$.trafficCop = function(url, options) {
var reqOptions = url, key;
if(arguments.length === 2) {
reqOptions = $.extend(true, options, { url: url });
}
key = JSON.stringify(reqOptions);
if(inProgress[key]) {
inProgress[key].successCallbacks.push(reqOptions.success);
inProgress[key].errorCallbacks.push(reqOptions.error);
return;
}
var remove = function() {
delete inProgress[key];
},
traffic = {
successCallbacks: [reqOptions.success],
errorCallbacks: [reqOptions.error],
success: function(response) {
$.each($(inProgress[key].successCallbacks), function(idx,item){ item(response); });
remove();
},
error: function(exception) {
$.each($(inProgress[key].errorCallbacks), function(idx,item){ item(exception); });
remove();
}
};
inProgress[key] = $.extend(true, {}, reqOptions, traffic);
$.ajax(inProgress[key]);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment