Backbone:在视图上限制集合过滤器事件

Ing*_*gro 4 ajax backbone.js underscore.js

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

问题是每次击键都会触发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();
    });
}
Run Code Online (Sandbox Code Playgroud)

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

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

nik*_*shr 12

每次发生keyup事件时调用的函数filter_collection本身都不受限制,你在里面创建的函数会被立即调用并丢弃.

您应该将事件绑定到受限制的函数:

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);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

_.debounce如果您愿意,您当然可以使用.请参阅http://jsfiddle.net/nikoshr/zWrgW/进行演示