Last active
December 14, 2015 16:29
-
-
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.
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
// 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