1

在某些地方,我们必须只运行一个函数实例。

这段代码对我有用:

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
    };
}
4

2 回答 2

2

您可能希望为此使用jQuery 的 `Deferred' 功能

function decorate(fn) {
    var deferred;
    return function(){
        if (!deferred) {
            deferred = new jQuery.Deferred;
            fn(deferred.resolve); // pass in the callback
        }
        return deferred;
    };
}

装饰函数将始终返回相同的 Deferred 对象,该对象将通过原始函数的回调解决 - 在第一次调用时开始。

于 2012-08-28T15:49:32.397 回答
0

像这样的东西?

function make_run_once(callback) {
    var deferred = false;
    return function () {
        if (false === deferred) {
            return;
        } else {
            deferred = $.Deferred();
            deferred.done(function () {
                deferred = false;
            });
            callback(deferred);  // pass deferred to callback so it can resolve at it's own leisure
        }
    };
}

var once = make_run_once(function (deferred) {
    // do stuff, possible ajax stuff
    setTimeout(function () {
        deferred.resolve();  // resolve at some point so it become unblocked again
    }, 100);
});
once(); // run
once(); // block
once(); // block
once(); // block
setTimeout(once, 500);  // run

那些“替换”其他请求的请求呢,你有吗?就像自动完成功能一样。您需要对其进行修改才能使其正常工作。与其忽略新请求,不如保留最新请求并在最后一个请求完成时触发它。

于 2012-08-28T13:00:59.710 回答