Trunk: Throttle collection filter event on view

In my application, I have a view displayed as a table containing a collection received from the server. I want the user to be able to filter this collection by writing a search string in a text box.

The problem is that the keyup event is for every key press, and I want to avoid this so as not to overload the server with useless requests. Therefore, I decided to use the underline throttle function, but I can not implement it in working mode.

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(); }); } 

Thus, the update_collection function is called for each keystroke, as before, without throttle . I also tried with debounce , but all requests will just start after a timeout. What am I missing?

Any help is appreciated, thanks!

+4
source share
2 answers

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

You must bind your event to a throttle 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 can, of course, use _.debounce if you want. And take a look at http://jsfiddle.net/nikoshr/zWrgW/ for a demo

+12
source

You can also bind to a change event, not a keyboard.

0
source

All Articles