gpt4 book ai didi

javascript - 发送 keyup 事件时如何避免竞争条件

转载 作者:行者123 更新时间:2023-11-29 10:50:19 25 4
gpt4 key购买 nike

我有一个函数 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));

最佳答案

我将采用一种不同的、可能矫枉过正的方法并使用 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);

还有一把 fiddle http://jsfiddle.net/EWSAV/1/

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com