3

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

3 回答 3

2

我将采用不同的,可能是矫枉过正的方法并使用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/

于 2012-07-11T14:35:53.333 回答
1

只要您运行同步操作,这应该没问题,因为事件会及时执行。

但是,您可以添加第二个变量来指示匹配是否正在进行中。

像这样的东西:

(function ($, UserCollection) {

    var userCollection;
    var inProgress = false;

    var matcher = function (request, response) {
        if (!inProgress){
           if (!userCollection) {
               inProgress = true;
               userCollection = new UserCollection();
               userCollection.fetch();
           } else {
               isMatched(request, response);
           }
           // inProgress = false; - after your asynchonous code is executed
        }
    };

    return matcher;
}(jquery, UserCollection));

这段代码可能不起作用,但我想你明白了。

但是,这种方法可能需要您的异步脚本在同一范围内才能访问inProgress. 更好的选择可能是在 fetch 上使用回调:

userCollection.fetch({ success:function(){inProgress=false} });
于 2012-07-11T14:05:53.473 回答
0

According to Backbone.js documentation, fetch() accepts a callback function to be called after a successful "fetch". So you can have a global variable indicating the state of the current "fetch". This is the basic idea, I think you can work your way from here

fetching = false;
//Event fired ->
if (!fetching ){
fetching = true;
..fetch({success: function(){fetching = false;}});
}
于 2012-07-11T14:09:53.360 回答