Permalink
Browse files

Implement ajax request delay to prevent flooding server with requests

  • Loading branch information...
1 parent 3aa2166 commit 82e3fd9fce9bc3c518ba61285b1e2cf1fff2ec97 @meltingice committed Jan 6, 2012
Showing with 19 additions and 21 deletions.
  1. +11 −19 lib/ajax-chosen.js
  2. +8 −2 src/ajax-chosen.coffee
View
@@ -1,4 +1,4 @@
-(function() {
+
(function($) {
return $.fn.ajaxChosen = function(options, callback) {
var select;
@@ -7,41 +7,33 @@
return this.next('.chzn-container').find(".search-field > input").bind('keyup', function() {
var field, val;
val = $.trim($(this).attr('value'));
- if (val.length < 3 || val === $(this).data('prevVal')) {
- return false;
- }
+ if (val.length < 3 || val === $(this).data('prevVal')) return false;
+ if (this.timer) clearTimeout(this.timer);
$(this).data('prevVal', val);
field = $(this);
options.data = {
term: val
};
- if (typeof success !== "undefined" && success !== null) {
- success;
- } else {
+ if (typeof success === "undefined" || success === null) {
success = options.success;
- };
+ }
options.success = function(data) {
var items;
- if (!(data != null)) {
- return;
- }
+ if (!(data != null)) return;
select.find('option').each(function() {
- if (!$(this).is(":selected")) {
- return $(this).remove();
- }
+ if (!$(this).is(":selected")) return $(this).remove();
});
items = callback(data);
$.each(items, function(value, text) {
return $("<option />").attr('value', value).html(text).appendTo(select);
});
select.trigger("liszt:updated");
field.attr('value', val);
- if (typeof success !== "undefined" && success !== null) {
- return success();
- }
+ if (typeof success !== "undefined" && success !== null) return success();
};
- return $.ajax(options);
+ return this.timer = setTimeout(function() {
+ return $.ajax(options);
+ }, 800);
});
};
})(jQuery);
-}).call(this);
View
@@ -25,6 +25,10 @@
# characters.
return false if val.length < 3 or val is $(this).data('prevVal')
+ # We delay searches by a small amount so that we don't flood the
+ # server with ajax requests.
+ clearTimeout(@timer) if @timer
+
# Set the current search term so we don't execute the ajax call if
# the user hits a key that isn't an input letter/number/symbol
$(this).data('prevVal', val)
@@ -75,6 +79,8 @@
# Finally, call the user supplied callback (if it exists)
success() if success?
- # Execute the ajax call to search for autocomplete data
- $.ajax(options)
+ # Execute the ajax call to search for autocomplete data with a timer
+ @timer = setTimeout ->
+ $.ajax(options)
+ , 800
)(jQuery)

0 comments on commit 82e3fd9

Please sign in to comment.