我有一个函数matcher,每次发送keyup事件时都会调用它。

该函数属于一个看起来像这样的模块(1)。
如果在提取完成之前又进行了另一个调用怎么办?
如何在本模块(1)中解决此问题?

(1)

(function ($, UserCollection) {

    var userCollection;

    var matcher = function (request, response) {
        if (!userCollection) {
            userCollection = new UserCollection();
            userCollection.fetch();
        } else {
            isMatched(request, response);
        }
    };

    return matcher;
}(jquery, UserCollection));

最佳答案

我将采用另一种方法,可能是矫kill过正,并使用jqXHR object returned by collection.fetch

var Matcher=(function($,UserCollection) {

    var xhr=null, userCollection=null;

    // matching against a defined ID for testing purpose
    function isMatched(id) {
        return userCollection.get(id);
    }

    // the request would be an ID in my example,
    // and the callback is the function invoked when the collection is fetched
    function matcher(request, callback) {
        if (!xhr) {
            userCollection = new UserCollection();

            // fetch returns a handy xhr object used for the deferred
            xhr=userCollection.fetch();
        }

        xhr.then(function() {
            callback(isMatched(request));
        });
    }

    return matcher;

})(jQuery, UserCollection);

如果xhr已解决,则立即调用回调,否则将在请求完成时进行:有关更多信息,请参见jQuery.Deferred

你会用它作为
Matcher(1,console.log);
Matcher(2,console.log);

和小提琴http://jsfiddle.net/EWSAV/1/

关于javascript - 发送按键事件时如何避免竞争状况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11433829/

10-13 08:53