Skip to content

Instantly share code, notes, and snippets.

@amessinger
Last active December 14, 2015 16:29
Show Gist options
  • Save amessinger/5115804 to your computer and use it in GitHub Desktop.
Save amessinger/5115804 to your computer and use it in GitHub Desktop.
Gives you the ability to create or override methods returning deferred objects so that only one request can be fired at a time.
// examples:
// create a new function : customRequest = Semaphore.request($.ajax);
// override a function: Backbone.sync = Semaphore.request(Backbone.sync);
Semaphore = function() {
// private attributes
var available = true;
// private api
function lock() {
available = false;
}
function unlock() {
available = true;
}
function getLock() {
var temp = available;
if (available) {
lock();
}
return temp;
}
// public api
var publicApi = {
// semaphored-request constructor
request: function(proto) {
return function() {
if (getLock()) {
var deferred = proto.apply(this, arguments);
deferred.complete(function() {
unlock();
});
}
else {
var deferred = null;
}
return deferred;
};
},
available: function() {
return available;
}
}
return publicApi;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment