4

在我的应用程序中,我有一个显示为表格的视图,其中包含从服务器获取的集合。我希望用户能够在文本框中写入搜索字符串来过滤此集合。

问题是每次击键都会触发 keyup 事件,我想避免这种情况,以免服务器因无用的请求而过载。所以我想使用下划线的油门功能,但我无法以有效的方式实现它。

events: {
    'keyup #filter' : 'filter_collection'
}

filter_collection: function(e) {
    var el, throttled, value;

    el = e.currentTarget;
    value = $(el).val();
    this.collection.server_api.filter = value;
    throttled = _.throttle(_.bind(this.update_collection, this), 5000);
    throttled();
}

update_collection: function() {
    var promise, self;

    self = this;
    promise = this.collection.fetch();
    $.when(promise).then(function() {
      self.collection.pager();
    });
}

这样,每次击键都会调用 update_collection 函数,就像之前没有throttle. 我也尝试过,debounce但所有请求都会在等待时间后触发。我错过了什么?

任何帮助表示赞赏,谢谢!

4

2 回答 2

12

The function called each time a keyup event occurs is filter_collection which is not itself throttled, the one you create inside is immediately called and discarded.

You should bind your event to a throttled function:

var V = Backbone.View.extend({
    events: {
        'keyup #filter' : 'filter_collection'
    },

    filter_collection: _.throttle(function(e) {
        var el, throttled, value;

        el = e.currentTarget;
        value = $(el).val();

        this.update_collection(value);
    }, 5000),

    update_collection: function(val) {
        var promise, self;
        self = this;
        promise = this.collection.fetch();
        $.when(promise).then(function() {
          console.log('fetched '+val);
        });
    }
});

You could of course use _.debounce if you prefer. And see http://jsfiddle.net/nikoshr/zWrgW/ for a demo

于 2013-03-29T17:16:59.067 回答
0

You could also bind to the change event rather than keyup.

于 2013-03-29T17:19:30.043 回答