在某些地方,我们必须只运行一个函数实例。
这段代码对我有用:
function example() {
var that = this;
if(that.running) {
return false;
}
that.running = true;
$.get(url, {}, function (data) {
that.running = false;
});
}
我们如何改进它,使其更可重用?
UPD这是基于 Frits van Campen 回答的解决方案:
function make_run_once(callback) {
callback.running = false;
return function () {
if(callback.running) {
return false;
}
callback.running = true;
deferred = $.Deferred();
deferred.done(function () {
callback.running = false;
});
callback(deferred); // pass deferred to callback so it can resolve at it's own leisure
};
}